package com.ktgj.flight.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.FlightOrderChangeConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.enums.EnumHelper;
import com.ktgj.common.core.utils.*;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.file.api.RemoteFilesService;
import com.ktgj.flight.common.linkstar.domain.searchFlight.one.FlightTransfer;
import com.ktgj.flight.common.qunar.domain.QnnarFlightSearchPriceResponse;
import com.ktgj.flight.common.ruili._DR;
import com.ktgj.flight.common.hangbanguanjia.HangBanGuanJia;
import com.ktgj.flight.common.huaxia._G5;
import com.ktgj.flight.common.linkstar.LinkStar;
import com.ktgj.flight.common.linkstar.domain.CalculateRefundRes;
import com.ktgj.flight.common.linkstar.domain.TicketInfoResponse;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.AirReIssuePriceRequest;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.ReIssuePriceResponse;
import com.ktgj.flight.common.linkstar.domain.calculation.CalculationResponse;
import com.ktgj.flight.common.linkstar.domain.changeFlight.ChangeFlightRequest;
import com.ktgj.flight.common.linkstar.domain.publishprice.FlightPublishPriceReqVo;
import com.ktgj.flight.common.linkstar.domain.publishprice.FlightPublishPriceResVo;
import com.ktgj.flight.common.linkstar.domain.stopfight.FightStopReqVo;
import com.ktgj.flight.common.linkstar.domain.stopfight.FightStopResVo;
import com.ktgj.flight.common.qunar._Qunar;
import com.ktgj.flight.common.spring._Spring;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.InterfaceEntity.*;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.mapper.*;
import com.ktgj.flight.service.*;
import com.ktgj.flight.vo.CabinInfoVo;
import com.ktgj.flight.vo.FlightResponseVo;
import com.ktgj.flight.vo.FlightVo;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.*;
import com.ktgj.sms.api.RemoteSmsService;
import com.ktgj.sms.api.domain.Sms;
import io.swagger.annotations.ApiModelProperty;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * 航线信息维护Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-30
 */
//@Transactional
@Service
public class FlightServiceImpl implements IFlightService {

    private final String FLIGHT = "flight:";

    @Autowired
    private RedisService redisService;

    @Autowired
    private FlightMapper flightMapper;

    @Autowired
    private _Qunar qunar; //去哪

    @Autowired
    private _Spring springFlight; //舂秋

    @Autowired
    private LinkStar linkStar; //领达

    @Autowired
    private HangBanGuanJia hangBanGuanJia; //航班管家

    @Autowired
    private _DR ruiLi; //瑞丽

    @Autowired
    private _G5 huaXia; //华夏

    @Autowired
    private IFlightOrderInfoService orderInfoService; //机票基本订单信息

    @Autowired
    private IFlightOrderInfoTicketsService orderInfoTicketsService; //机票订单明细

    @Autowired
    private FlightOrderInfoTicketsMapper flightOrderInfoTicketsMapper;

    @Autowired
    private RemoteCustomerService customerService; //远程获取会员信息

    @Autowired
    private IAirportService airportService; //机场信息

    @Autowired
    private IFlightInterfaceService interfaceService; //渠道从表

    @Autowired
    private IFlightChannelRuleService channelRuleService; //渠道主表

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private IAirlinerService airlinerService;

    @Autowired
    private AirlinerMapper airlinerMapper;

    @Autowired
    private IPlaneTypeService planeTypeService;

    @Autowired
    private IFlightRevisecabinpriceService revisecabinpriceService; //机票产品直降产品政策

    @Autowired
    private IFlightOutticketLogService outticketLogService;

    @Autowired
    private RemotePayService remotePayService;

    @Autowired
    private IFlightCabinruleService flightCabinruleService;

    @Autowired
    private IFlightOrderChangeService orderChangeService;

    @Autowired
    private IFlightOrderChangeTicketsService changeTicketsService;

    @Autowired
    private FlightOrderInfoMapper flightOrderInfoMapper;

    @Autowired
    private IFlightService flightService;

    @Autowired
    private RemoteFilesService filesService;

    @Autowired
    private FlightOrderCashInfoMapper flightOrderCashInfoMapper;

    @Autowired
    private RemoteSmsService remoteSmsService;

    @Autowired
    private IFlightOrderExceptionService flightOrderExceptionService;

    @Autowired
    private FinanceConsignPymtRecordMapper financeConsignPymtRecordMapper;

    @Autowired
    private IFlightOrderAssistService flightOrderAssistService;

    @Autowired
    private FlightOrderInvoiceMapper flightOrderInvoiceMapper;

    @Autowired
    private FlightOrderIternaryMapper flightOrderIternaryMapper;

    @Autowired
    private FlightDeliverAssignMapper flightDeliverAssignMapper;


    /**
     * 查询航线信息维护
     *
     * @param flightId 航线信息维护ID
     * @return 航线信息维护
     */
    @Override
    public Flight selectFlightById(Long flightId) {
        return flightMapper.selectFlightById(flightId);
    }

    /**
     * 查询航线信息维护列表
     *
     * @param flight 航线信息维护
     * @return 航线信息维护
     */
    @Override
    public List<Flight> selectFlightList(Flight flight) {
        return flightMapper.selectFlightList(flight);
    }

    /**
     * 新增航线信息维护
     *
     * @param flight 航线信息维护
     * @return 结果
     */
    @Override
    public int insertFlight(Flight flight) {
        return flightMapper.insertFlight(flight);
    }

    /**
     * 修改航线信息维护
     *
     * @param flight 航线信息维护
     * @return 结果
     */
    @Override
    public int updateFlight(Flight flight) {
        return flightMapper.updateFlight(flight);
    }

    /**
     * 批量删除航线信息维护
     *
     * @param flightIds 需要删除的航线信息维护ID
     * @return 结果
     */
    @Override
    public int deleteFlightByIds(Long[] flightIds) {
        return flightMapper.deleteFlightByIds(flightIds);
    }

    /**
     * 删除航线信息维护信息
     *
     * @param flightId 航线信息维护ID
     * @return 结果
     */
    @Override
    public int deleteFlightById(Long flightId) {
        return flightMapper.deleteFlightById(flightId);
    }


    @Override
    public List<FlightResponseVo> getFlightInfoListBySearchCondition(Customer customer, MoFlightSearchRequest searchRequest) throws Exception {
        List<FlightResponseVo> flightVos = null;
        Object redisData;
        String depDate = searchRequest.GoSearchWhere.DepDate;
        String dstAirport = searchRequest.GoSearchWhere.DstAirport;
        String orgAirport = searchRequest.GoSearchWhere.OrgAirport;
        searchRequest.hasKeyCustomers = false;

        if (searchRequest.TripType == EnumHelper.TripType.单程.getValue()) {
            //缓存key
            String redisKey = depDate + dstAirport + orgAirport;
            //先判断缓存中是否存在此次查询的结果
            redisData = redisService.getCacheObject(FLIGHT + redisKey);
            //flightVos = handleRequest(searchRequest);
            if(redisData!=null) {
                //获取缓存数据
                String string = JSON.toJSONString(redisData);
                String str= JSON.parse(string).toString();
                flightVos = JSONArray.parseArray(str, FlightResponseVo.class);
                return flightVos;
            } else {
                //查询接口数据
                flightVos= handleRequest(searchRequest, customer);
                //判断接口是否返回数据
                if(flightVos!=null && flightVos.size()>0){
                    //放入缓存(10分钟)
                    String jsonString = JSON.toJSONString(flightVos, SerializerFeature.DisableCircularReferenceDetect);
                    redisService.setCacheObject(FLIGHT+redisKey, jsonString,10L, TimeUnit.MINUTES);
                }
                return flightVos;
            }

        } else if (searchRequest.TripType == EnumHelper.TripType.往返.getValue()) {
            String backDepDate = searchRequest.BackSearchWhere.DepDate;
            String backRedisKey = depDate + dstAirport + orgAirport + backDepDate;
            //先判断缓存中是否存在此次查询的结果
            redisData = redisService.getCacheObject(FLIGHT + backRedisKey);
            //flightVos = handleRequest(searchRequest);
            if (redisData != null) {
                //获取缓存数据
                String string = JSON.toJSONString(redisData);
                String str = JSON.parse(string).toString();
                flightVos = JSONArray.parseArray(str, FlightResponseVo.class);
                return flightVos;

            } else {
                //查询接口数据
                flightVos = handleRequest(searchRequest, customer);
                //判断接口是否返回数据
                if (flightVos != null && flightVos.size() > 0) {
                    //放入缓存(10分钟)
                    String jsonString = JSON.toJSONString(flightVos, SerializerFeature.DisableCircularReferenceDetect);
                    redisService.setCacheObject(FLIGHT + backRedisKey, jsonString, 10L, TimeUnit.MINUTES);
                }
                return flightVos;
            }
        }
        return flightVos;
    }

    //app往返查询
    @Override
    public List<FlightVo> getFlightInfoList(Customer customer, MoFlightSearchRequest searchRequest) throws Exception {
        List<FlightVo> flight = new ArrayList<>();
        List<FlightResponseVo> flightVos = null;
        Object redisData;
        String depDate = searchRequest.GoSearchWhere.DepDate;
        String dstAirport = searchRequest.GoSearchWhere.DstAirport;
        String orgAirport = searchRequest.GoSearchWhere.OrgAirport;
        searchRequest.TripType = 2;
        searchRequest.hasKeyCustomers = false;
        String backDepDate = searchRequest.BackSearchWhere.DepDate;
        String backRedisKey = depDate + dstAirport + orgAirport + backDepDate;
        //先判断缓存中是否存在此次查询的结果
        redisData = redisService.getCacheObject(FLIGHT + backRedisKey);
        Set<String> set = new HashSet<>();
        if (redisData != null) {
            //获取缓存数据
            String string = JSON.toJSONString(redisData);
            String str = JSON.parse(string).toString();
            flightVos = JSONArray.parseArray(str, FlightResponseVo.class);
            flightVos.forEach(item -> {
                item.flightVos.forEach(items -> {
                    if (set.add(items.getFlightNo())) {
                        FlightVo vo = new FlightVo();
                        BeanUtils.copyProperties(items, vo);
                        vo.getListCabinInfo().addAll(items.getListCabinInfo());
                        vo.getLstCabinGroup().addAll(items.getLstCabinGroup());
                        flight.add(vo);
                    }
                });
            });
        } else {
            //查询接口数据
            flightVos = handleRequest(searchRequest, customer);
            //判断接口是否返回数据
            if (flightVos.size() > 0) {
                //放入缓存(10分钟)
                redisService.setCacheObject(FLIGHT + backRedisKey, JSON.toJSONString(flightVos), 10L, TimeUnit.MINUTES);
            }
            flightVos.forEach(item -> {
                item.flightVos.forEach(items -> {
                    if (set.add(items.getFlightNo())) {
                        FlightVo vo = new FlightVo();
                        BeanUtils.copyProperties(items, vo);
                        vo.getListCabinInfo().addAll(items.getListCabinInfo());
                        vo.getLstCabinGroup().addAll(items.getLstCabinGroup());
                        flight.add(vo);
                    }
                });
            });
        }
        return flight;
    }

    //app往返查询返程
    @Override
    public List<FlightVo> getFlightInfoListBack(Customer customer, MoFlightSearchRequest searchRequest) throws Exception {
        List<FlightVo> flight = new ArrayList<>();
        List<FlightResponseVo> flightVos = null;
        Object redisData;
        String depDate = searchRequest.GoSearchWhere.DepDate;
        String dstAirport = searchRequest.GoSearchWhere.DstAirport;
        String orgAirport = searchRequest.GoSearchWhere.OrgAirport;
        String backDepDate = searchRequest.BackSearchWhere.DepDate;
        String backRedisKey = depDate + dstAirport + orgAirport + backDepDate;
        //先判断缓存中是否存在此次查询的结果
        redisData = redisService.getCacheObject(FLIGHT + backRedisKey);
        if (redisData != null) {
            //获取缓存数据
            String string = JSON.toJSONString(redisData);
            String str = JSON.parse(string).toString();
            flightVos = JSONArray.parseArray(str, FlightResponseVo.class);
            flightVos.forEach(goFlight -> {
                goFlight.backFlightVos.forEach(backFlight -> {
                    /*if (backFlight.getFlightNo().substring(0, 2).equals(searchRequest.FlightNo.substring(0, 2)) && backFlight.getChannelType() == searchRequest.channelType) {
                        flight.add(backFlight);
                    }*/
                    flight.add(backFlight);
                });
            });
        }
        return flight;
    }

    //航班详情（单程）
    @Override
    public FlightVo flightDetails(Customer customer, MoFlightSearchRequest searchRequest) {
        try {
            searchRequest.TripType = 1;
            searchRequest.hasKeyCustomers = false;
            if (searchRequest.GoSearchWhere.channelType == EnumHelper.RequestType.Qunar.getValue()) {
                FlightVo flightVo = new FlightVo();
                QnnarFlightSearchPriceResponse response = qunar._FlightSearchPrice(searchRequest.GoSearchWhere.OrgAirport, searchRequest.GoSearchWhere.DstAirport, searchRequest.GoSearchWhere.DepDate, searchRequest.GoSearchWhere.FlightNo, searchRequest.BackSearchWhere.DepDate);
                SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
                Date bTime = dateFormat.parse(response.result.btime);
                Date eTime = dateFormat.parse(response.result.etime);
                if (bTime.compareTo(eTime) > 0) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(format.parse(response.result.date));
                    calendar.add(Calendar.DATE, 1);
                    Date date = calendar.getTime();
                    flightVo.setArrDate(format.format(date) + " " + response.result.etime);
                    flightVo.setArrad(1);
                } else if (bTime.compareTo(eTime) < 0) {
                    flightVo.setArrDate(response.result.date + " " + response.result.etime);
                }
                flightVo.setDepDate(response.result.date + " " + response.result.btime);
                flightVo.setChannelType(EnumHelper.RequestType.Qunar.getValue());
                flightVo.setFuelTax(response.result.tof);
                flightVo.setAirportTax(response.result.arf);
                flightVo.setAirline(response.result.carrier);
                flightVo.setAirlineGif(filesService.airlineLogo() + response.result.carrier + ".gif");
                flightVo.setFlightNo(response.result.code);
                flightVo.setDstAirport(response.result.arrCode);
                flightVo.setDstAirportName(response.result.arrAirport);
                flightVo.setOrgAirport(response.result.depCode);
                flightVo.setOrgAirportName(response.result.depAirport);
                flightVo.setArrTerm(response.result.arrTerminal);
                flightVo.setDepTerm(response.result.depTerminal);
                flightVo.setTPM(response.result.distance);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date depDate = simpleDateFormat.parse(flightVo.getDepDate());
                Date arrDate = simpleDateFormat.parse(flightVo.getArrDate());

                //计算飞行时长
                long diff = arrDate.getTime() - depDate.getTime();
                long diffMinutes = diff / (60 * 1000) % 60;
                long diffHours = diff / (60 * 60 * 1000) % 24;

                String flightTimes = "";
                if (diffHours == 0) {
                    flightTimes = diffMinutes + "分钟";
                } else if (diffMinutes == 0) {
                    flightTimes = diffHours + "小时";
                } else if (diffHours != 0 && diffMinutes != 0) {
                    flightTimes = diffHours + "小时" + diffMinutes + "分钟";
                }
                flightVo.setFlightTimes(flightTimes);
                String correct = response.result.correct;
                correct = correct.replace("%", "");
                Float oat = Float.valueOf(correct) / 100;
                flightVo.setPunctualityRate(new BigDecimal(oat));
                PlaneType planeType = planeTypeService.selectPlaneTypeByTypeId(response.result.flightType);
                if (planeType != null) {
                    flightVo.setPlaneStyle(planeType.getAirlineType());
                    flightVo.setPlaneTypeDesc(planeType.getPlaneTypeDesc());
                    flightVo.setWidthType(planeType.getWidthType());
                } else {
                    flightVo.setPlaneStyle(null);
                    flightVo.setPlaneTypeDesc(response.result.flightType);
                    flightVo.setWidthType(null);
                }
                flightVo.setCodeShare(response.result.codeShare);
                flightVo.setStopCount(response.result.stopsNum);
                if (response.result.stopsNum > 0) {
                    flightVo.setStopPlace(response.result.stopCityName);
                    Date depTime = simpleDateFormat.parse(response.result.stopInfoList.get(0).dptDate + " " + response.result.stopInfoList.get(0).dptTime);
                    Date arrTime = simpleDateFormat.parse(response.result.stopInfoList.get(0).arrDate + " " + response.result.stopInfoList.get(0).arrTime);
                    //计算经停时长
                    long diffStop = arrTime.getTime() - depTime.getTime();
                    long diffMinutesStop = diffStop / (60 * 1000) % 60;
                    long diffHoursStop = diffStop / (60 * 60 * 1000) % 24;
                    String stopTimes = "";
                    if (diffHoursStop == 0) {
                        stopTimes = diffMinutesStop + "分钟";
                    } else if (diffMinutesStop == 0) {
                        stopTimes = diffHoursStop + "小时";
                    } else if (diffHoursStop != 0 && diffMinutesStop != 0) {
                        stopTimes = diffHoursStop + "小时" + diffMinutesStop + "分钟";
                    }
                    flightVo.setStopTime(stopTimes);
                }

                if (response.result.meal)
                    flightVo.setMeal("有餐食");
                else
                    flightVo.setMeal("无餐食");
                response.result.vendors.forEach(item -> {
                    CabinInfoVo cabinInfoVo = new CabinInfoVo();
                    cabinInfoVo.setCabin(item.cabin);
                    cabinInfoVo.setPrice(item.barePrice);
                    cabinInfoVo.setTagName(item.tagName);
                    if (item.cabinType == 0 || item.cabinType == 4) {
                        cabinInfoVo.setBaseCabin("Y");
                        cabinInfoVo.setBaseCabinName("经济舱");
                    } else if (item.cabinType == 1) {
                        cabinInfoVo.setBaseCabin("F");
                        cabinInfoVo.setBaseCabinName("头等舱");
                    } else if (item.cabinType == 2) {
                        cabinInfoVo.setBaseCabin("C");
                        cabinInfoVo.setBaseCabinName("商务舱");
                    } else if (item.cabinType == 3) {
                        cabinInfoVo.setBaseCabin("Y");
                        cabinInfoVo.setBaseCabinName("经济舱精选");
                    } else if (item.cabinType == 5) {
                        cabinInfoVo.setBaseCabin("F");
                        cabinInfoVo.setBaseCabinName("超值头等舱");
                    }
                    if ("A".equals(item.cabinCount)) {
                        cabinInfoVo.setCabinLeftDesc("座位充足");
                    } else {
                        cabinInfoVo.setCabinLeftDesc(item.cabinCount);
                    }

                    if (cabinInfoVo.getBaseCabin() != null && !cabinInfoVo.getBaseCabin().equals("")) {

                        List<FlightCabinrule> cabinrules = flightCabinruleService.queryFlightCabinRule(response.result.carrier, cabinInfoVo.getCabin().substring(0,1));
                        if (cabinrules != null && cabinrules.size() > 0) {
                            FlightCabinrule cabinrule = cabinrules.get(0);
                            cabinInfoVo.setBaggage(cabinrule.getBaggage());
                            /*cabinInfoVo.setRefund(cabinrule.getRefund());
                            cabinInfoVo.setChange(cabinrule.getChange());*/
                        }
                    }
                    flightVo.getListCabinInfo().add(cabinInfoVo);
                });

                if (customer != null) {
                    List<FlightRevisecabinprice> revisecabinprices = revisecabinpriceService.selectReviseCabinByCustomerIdCard(customer.getCustCertificateNo());
                    if (revisecabinprices != null && revisecabinprices.size() > 0) {
                        for (FlightRevisecabinprice revisecabinprice : revisecabinprices) {
                            if (response.result.carrier.equals(revisecabinprice.getAirlinerId())) {
                                flightVo.setReturnMoney(String.valueOf(revisecabinprice.getReturnMoney()));
                                flightVo.setSaleSexPlain(revisecabinprice.getSalesexplain());
                                /*String cabin = revisecabinprice.getCabin();
                                String[] splCabin = cabin.split(",");
                                for (String spl : splCabin) {
                                    if (cabinInfo.Cabin.equals(spl)) {
                                        infoVo.setReturnMoney(String.valueOf(revisecabinprice.getReturnMoney()));
                                    }
                                }*/
                            }
                        }
                    } else {
                        List<FlightRevisecabinprice> reviseCabin = revisecabinpriceService.queryReviseCabin();
                        for (FlightRevisecabinprice revisecabinprice : reviseCabin) {
                            if (response.result.carrier.equals(revisecabinprice.getAirlinerId())) {
                                flightVo.setReturnMoney(String.valueOf(revisecabinprice.getReturnMoney()));
                                flightVo.setSaleSexPlain(revisecabinprice.getSalesexplain());
                                /*String cabin = revisecabinprice.getCabin();
                                String[] splCabin = cabin.split(",");
                                for (String spl : splCabin) {
                                    if (cabinInfo.Cabin.equals(spl)) {
                                        infoVo.setReturnMoney(String.valueOf(revisecabinprice.getReturnMoney()));
                                    }
                                }*/
                            }
                        }
                    }
                }
                List<CabinInfoVo> lstCabinY = new ArrayList<>();
                List<CabinInfoVo> lstCabinC = new ArrayList<>();
                List<CabinInfoVo> lstCabinF = new ArrayList<>();
                for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                    if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                        continue;
                    }
                    if (cabinInfoVo.getBaseCabin().equals("Y")) {
                        lstCabinY.add(cabinInfoVo);
                    }
                    if (cabinInfoVo.getBaseCabin().equals("C")) {
                        lstCabinC.add(cabinInfoVo);
                    }
                    if (cabinInfoVo.getBaseCabin().equals("F")) {
                        lstCabinF.add(cabinInfoVo);
                    }
                }
                flightVo.getLstCabinGroup().add(lstCabinY);
                flightVo.getLstCabinGroup().add(lstCabinC);
                flightVo.getLstCabinGroup().add(lstCabinF);
                return flightVo;
            } else {
                List<FlightResponseVo> responseVos = getFlightInfoListBySearchCondition(customer, searchRequest);
                List<FlightVo> flightVoList = new ArrayList<>();
                for (FlightResponseVo responseVo : responseVos) {
                    for (FlightVo flightVo : responseVo.flightVos) {
                        if (flightVo.getFlightNo().equals(searchRequest.GoSearchWhere.FlightNo)) {
                            flightVoList.add(flightVo);
                        }
                    }
                }
                for (FlightVo flightVo : flightVoList) {
                    if (searchRequest.GoSearchWhere.channelType == flightVo.getChannelType()) {
                        return flightVo;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //航班详情中转
    @Override
    public FlightTransfer flightTransfers(Customer customer, String transferId, String depDate, String dstAirport, String orgAirport) {
        try {
            MoFlightSearchRequest searchRequest = new MoFlightSearchRequest();
            searchRequest.GoSearchWhere.OrgAirport = orgAirport;
            searchRequest.GoSearchWhere.DstAirport = dstAirport;
            searchRequest.GoSearchWhere.DepDate = depDate;
            searchRequest.TripType = 1;
            List<FlightResponseVo> responseVos = getFlightInfoListBySearchCondition(customer, searchRequest);
            FlightTransfer flightTransfers = new FlightTransfer();
            for (FlightResponseVo responseVo : responseVos) {
                for (FlightTransfer flightTransfer : responseVo.flightTransfers) {
                    if (flightTransfer.transferId.equals(transferId)) {

                        FlightVo flightVo = flightTransfer.flightVoList.get(0);
                        FlightVo flightVos = flightTransfer.flightVoList.get(1);

                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String stopTime = null;

                        String arrTime = flightVo.getArrDate();
                        String depTime = flightVos.getDepDate();

                        Date arr = format.parse(arrTime);
                        Date dep = format.parse(depTime);

                        long diff = dep.getTime() - arr.getTime();
                        long diffMinutes = diff / (60 * 1000) % 60;
                        long diffHours = diff / (60 * 60 * 1000) % 24;
                        long diffDays = diff / (24 * 60 * 60 * 1000);
                        StringBuffer stringBuffer = new StringBuffer();
                        if (diffDays > 0) {
                            diffHours = diffDays * 24 + diffHours;
                            stringBuffer.append(diffHours + "时");
                            stringBuffer.append(diffMinutes + "分");
                            stopTime = stringBuffer.toString();
                        } else {
                            stringBuffer.append(diffHours + "时");
                            stringBuffer.append(diffMinutes + "分");
                            stopTime = stringBuffer.toString();
                        }

                        for (FlightVo vo : flightTransfer.flightVoList) {
                            vo.setStopTime(stopTime);
                        }
                        flightTransfers = flightTransfer;
                    }
                }
            }
            return flightTransfers;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //航班详情（往返）
    @Override
    public FlightResponseDTO flightReturn(Customer customer, MoFlightSearchRequest searchRequest) {
        try {
            FlightResponseDTO responseDTO = new FlightResponseDTO();
            searchRequest.TripType = 2;
            searchRequest.hasKeyCustomers = false;
            List<FlightResponseVo> responseVos = getFlightInfoListBySearchCondition(customer, searchRequest);
            List<FlightVo> flightVoList = new ArrayList<>();
            for (FlightResponseVo responseVo : responseVos) {
                for (FlightVo flightVo : responseVo.flightVos) {
                    if (flightVo.getFlightNo().equals(searchRequest.GoSearchWhere.FlightNo)) {
                        flightVoList.add(flightVo);
                    }
                }
            }
            List<FlightVo> backFlightVoList = new ArrayList<>();
            for (FlightResponseVo responseVo : responseVos) {
                for (FlightVo flightVo : responseVo.backFlightVos) {
                    if (flightVo.getFlightNo().equals(searchRequest.BackSearchWhere.FlightNo)) {
                        backFlightVoList.add(flightVo);
                    }
                }
            }
            for (FlightVo flightVo : flightVoList) {
                if (searchRequest.GoSearchWhere.channelType == flightVo.getChannelType()) {
                    responseDTO.flightVos = flightVo;
                }
            }
            for (FlightVo flightVo : backFlightVoList) {
                if (searchRequest.BackSearchWhere.channelType == flightVo.getChannelType()) {
                    responseDTO.backFlightVos = flightVo;
                }
            }
            return responseDTO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<FlightResponseVo> handleRequest(MoFlightSearchRequest searchRequest, Customer customer) throws ExecutionException, InterruptedException {
        List<MoFlightSearchResponse> flightSearchResponseList = new ArrayList<>();

        //创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,
                10,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(1),
                Executors.defaultThreadFactory(), (r, executors) -> {
            System.out.println("无法处理的任务：" + r.toString());
        }) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println(System.currentTimeMillis() + "," + t.getName() + ",开始执行任务:" + r.toString());
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {

                System.out.println(System.currentTimeMillis() + "," + Thread.currentThread().getName() + ",任务:" + r.toString() + "，执行完毕!");
            }

            @Override
            protected void terminated() {
                System.out.println(System.currentTimeMillis() + "," + Thread.currentThread().getName() + "，关闭线程池!");
            }
        };


        //领达
        CompletableFuture<Void> linkStarThread = CompletableFuture.runAsync(() -> {
            MoFlightSearchResponse linkResponse = linkStar._FlightSearch(searchRequest);
            linkResponse.channelType = EnumHelper.RequestType.LinkStar.getValue();
            if (linkResponse != null) {
                flightSearchResponseList.add(linkResponse);
            }

        }, executor);

        //去哪
        CompletableFuture<Void> qunarThread = CompletableFuture.runAsync(() -> {
            MoFlightSearchResponse qunarResponse = qunar._FlightSearch(searchRequest);
            qunarResponse.channelType = EnumHelper.RequestType.Qunar.getValue();
            if (qunarResponse != null) {
                flightSearchResponseList.add(qunarResponse);
            }
        }, executor);


        //航班管家
        /*CompletableFuture<Void> hangBanGuanJiaThread = CompletableFuture.runAsync(() -> {
            MoFlightSearchResponse hbResponse = hangBanGuanJia.flightSearch(searchRequest);
            hbResponse.channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
            flightSearchResponseList.add(hbResponse);
        }, executor);*/


        //华夏
        CompletableFuture<Void> huaXiaThread = CompletableFuture.runAsync(() -> {
            MoFlightSearchResponse hxResponse = huaXia._FlightSearch(searchRequest);
            hxResponse.channelType = EnumHelper.RequestType.G5.getValue();
            flightSearchResponseList.add(hxResponse);
        }, executor);

        //春秋
        CompletableFuture<Void> springThread = CompletableFuture.runAsync(() -> {
            MoFlightSearchResponse springResponse = springFlight._FlightSearch(searchRequest);
            springResponse.channelType = EnumHelper.RequestType.Spring.getValue();
            flightSearchResponseList.add(springResponse);
        }, executor);

        //瑞丽
        CompletableFuture<Void> ruiLiThread = CompletableFuture.runAsync(() -> {
            MoFlightSearchResponse ruiLiResponse = ruiLi._FlightSearch(searchRequest);
            ruiLiResponse.channelType = EnumHelper.RequestType.DR.getValue();
            flightSearchResponseList.add(ruiLiResponse);
        }, executor);

        CompletableFuture.allOf(linkStarThread, qunarThread, huaXiaThread, springThread, ruiLiThread).get();

        List<FlightResponseVo> flightResponseVos = flightData(flightSearchResponseList, customer);

        return flightResponseVos;
    }

    private List<FlightResponseVo> flightData(List<MoFlightSearchResponse> flightSearchResponseList, Customer customer) {
        List<FlightResponseVo> list = new ArrayList<>();
        String logo = filesService.airlineLogo();
        List<FlightRevisecabinprice> revisecabinprices = null;
        if (customer != null) {
            revisecabinprices = revisecabinpriceService.selectReviseCabinByCustomerIdCard(customer.getCustCertificateNo());
            if (revisecabinprices == null)
                revisecabinprices = revisecabinpriceService.queryReviseCabin();
        } else {
            revisecabinprices = revisecabinpriceService.queryReviseCabin();
        }
        List<Airliner> airliners = airlinerMapper.selectAirlinerList(null);
        for (MoFlightSearchResponse item : flightSearchResponseList) {
            if (item.channelType == EnumHelper.RequestType.LinkStar.getValue()) {
                FlightResponseVo responseVo = new FlightResponseVo();
                List<FlightVo> linkListVo = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.LinkStar.getValue(), revisecabinprices, airliners);
                List<FlightVo> linkBackListVo = getFlightListVo(item.ListBackFlightInfo, logo, EnumHelper.RequestType.LinkStar.getValue(), revisecabinprices, airliners);
                List<FlightVo> linkTransferFlightVo = getFlightListVo(item.transferFlightInfo, logo, EnumHelper.RequestType.LinkStar.getValue(), revisecabinprices, airliners);
                if (linkListVo.size() > 0 && linkBackListVo.size() == 0 && linkTransferFlightVo.size() == 0) {
                    responseVo.flightVos = linkListVo;
                    list.add(responseVo);
                }
                if (linkListVo.size() > 0 && linkBackListVo.size() == 0 && linkTransferFlightVo.size() > 1 && linkTransferFlightVo.size() % 2 == 0) {
                    List<FlightTransfer> flightTransfers = new ArrayList<>();
                    do {
                        FlightTransfer flightTransfer = new FlightTransfer();
                        List<FlightVo> flightVos = new ArrayList<>();

                        FlightVo fv = new FlightVo();
                        BeanUtils.copyProperties(linkTransferFlightVo.get(0), fv);
                        fv.getListCabinInfo().addAll(linkTransferFlightVo.get(0).getListCabinInfo());
                        flightVos.add(fv);
                        FlightVo fv2 = new FlightVo();
                        BeanUtils.copyProperties(linkTransferFlightVo.get(1), fv2);
                        fv2.getListCabinInfo().addAll(linkTransferFlightVo.get(0).getListCabinInfo());
                        flightVos.add(fv2);

                        linkTransferFlightVo.remove(0);
                        linkTransferFlightVo.remove(0);

                        flightTransfer.flightVoList = flightVos;
                        flightTransfers.add(flightTransfer);
                    } while (linkTransferFlightVo.size() > 0);
                    responseVo.flightVos = linkListVo;
                    responseVo.flightTransfers = flightTransfers;
                    list.add(responseVo);
                }
                if (linkListVo.size() > 0 && linkBackListVo.size() == 0 && linkTransferFlightVo.size() > 1 && linkTransferFlightVo.size() % 2 != 0) {
                    responseVo.flightVos = linkListVo;
                    list.add(responseVo);
                }
                if (linkListVo.size() == 0 && linkBackListVo.size() == 0 && linkTransferFlightVo.size() > 1 && linkTransferFlightVo.size() % 2 == 0) {
                    List<FlightTransfer> flightTransfers = new ArrayList<>();
                    do {
                        FlightTransfer flightTransfer = new FlightTransfer();
                        List<FlightVo> flightVos = new ArrayList<>();

                        FlightVo fv = new FlightVo();
                        BeanUtils.copyProperties(linkTransferFlightVo.get(0), fv);
                        fv.getListCabinInfo().addAll(linkTransferFlightVo.get(0).getListCabinInfo());
                        flightVos.add(fv);
                        FlightVo fv2 = new FlightVo();
                        BeanUtils.copyProperties(linkTransferFlightVo.get(1), fv2);
                        fv2.getListCabinInfo().addAll(linkTransferFlightVo.get(0).getListCabinInfo());
                        flightVos.add(fv2);

                        linkTransferFlightVo.remove(0);
                        linkTransferFlightVo.remove(0);

                        flightTransfer.flightVoList = flightVos;
                        flightTransfers.add(flightTransfer);
                    } while (linkTransferFlightVo.size() > 0);
                    responseVo.flightTransfers = flightTransfers;
                    list.add(responseVo);
                }
                if (linkBackListVo.size() > 0 && linkListVo.size() > 0) { //往返组合
                    responseVo.backFlightVos = linkBackListVo;
                    responseVo.flightVos = linkListVo;
                    list.add(responseVo);
                }
            } else if (item.channelType == EnumHelper.RequestType.Qunar.getValue()) {
                FlightResponseVo responseVo = new FlightResponseVo();
                List<FlightVo> quarListVo = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.Qunar.getValue(), revisecabinprices, airliners);
                List<FlightVo> quarBackListVo = getFlightListVo(item.ListBackFlightInfo, logo, EnumHelper.RequestType.Qunar.getValue(), revisecabinprices, airliners);
                //List<FlightVo> quarListVoApp = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.Qunar.getValue(), revisecabinprices);
                if (quarListVo.size() > 0 && quarBackListVo.size() == 0) {
                    responseVo.flightVos = quarListVo;
                    //list.add(responseVo);
                }
                if (quarBackListVo.size() > 0 && quarListVo.size() > 0) { //往返组合
                    responseVo.backFlightVos = quarBackListVo;
                    responseVo.flightVos = quarListVo;
                    //responseVo.flightVosApp = quarListVo;
                    //list.add(responseVo);
                }
            } else if (item.channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
                FlightResponseVo responseVo = new FlightResponseVo();
                List<FlightVo> hbListVo = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.HangBanGuanJia.getValue(), revisecabinprices, airliners);
                if (hbListVo.size() > 0) {
                    responseVo.flightVos = hbListVo;
                    //list.add(responseVo);
                }
            } else if (item.channelType == EnumHelper.RequestType.G5.getValue()) {
                FlightResponseVo responseVo = new FlightResponseVo();
                List<FlightVo> hxListVo = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.G5.getValue(), revisecabinprices, airliners);
                if (hxListVo.size() > 0) {
                    responseVo.flightVos = hxListVo;
                    //list.add(responseVo);
                }
            } else if (item.channelType == EnumHelper.RequestType.Spring.getValue()) {
                FlightResponseVo responseVo = new FlightResponseVo();
                List<FlightVo> flightListVo = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.Spring.getValue(), revisecabinprices, airliners);
                List<FlightVo> backFlightListVo = getFlightListVo(item.ListBackFlightInfo, logo, EnumHelper.RequestType.Spring.getValue(), revisecabinprices, airliners);
                if (flightListVo.size() > 0 && backFlightListVo.size() == 0) {
                    responseVo.flightVos = flightListVo;
                    list.add(responseVo);
                }
                if (flightListVo.size() > 0 && backFlightListVo.size() > 0) {
                    responseVo.flightVos = flightListVo;
                    responseVo.backFlightVos = backFlightListVo;
                    //responseVo.flightVosApp = flightListVo;
                    list.add(responseVo);
                }
            } else if (item.channelType == EnumHelper.RequestType.DR.getValue()) {
                FlightResponseVo responseVo = new FlightResponseVo();
                List<FlightVo> flightListVo = getFlightListVo(item.ListGoFlightInfo, logo, EnumHelper.RequestType.DR.getValue(), revisecabinprices, airliners);
                List<FlightVo> backFlightListVo = getFlightListVo(item.ListBackFlightInfo, logo, EnumHelper.RequestType.DR.getValue(), revisecabinprices, airliners);
                if (flightListVo.size() > 0 && backFlightListVo.size() == 0) {
                    responseVo.flightVos = flightListVo;
                    //list.add(responseVo);
                }
                if (flightListVo.size() > 0 && backFlightListVo.size() > 0) {
                    responseVo.flightVos = flightListVo;
                    responseVo.backFlightVos = backFlightListVo;
                    //list.add(responseVo);
                }
            }
        }
        FlightResponseVo allData = new FlightResponseVo();
        for (FlightResponseVo flightResponseVo : list) {
            allData.flightVos.addAll(flightResponseVo.flightVos);
            if (flightResponseVo.backFlightVos != null && flightResponseVo.backFlightVos.size() > 0) {
                //allData.flightVosApp.addAll(flightResponseVo.flightVosApp);
                allData.backFlightVos.addAll(flightResponseVo.backFlightVos);
            }
            if (flightResponseVo.flightTransfers != null && flightResponseVo.flightTransfers.size() > 0) {
                allData.flightTransfers.addAll(flightResponseVo.flightTransfers);
            }
        }
        list.clear();
        list.add(allData);
        for (FlightResponseVo flight : list) {
            if (flight.flightVos != null && flight.flightVos.size() > 0 && flight.backFlightVos.size() == 0) {
                /*for (FlightVo flightVo : flight.flightVos) {
                    List<CabinInfoVo> lstCabinY = new ArrayList<>();
                    List<CabinInfoVo> lstCabinC = new ArrayList<>();
                    List<CabinInfoVo> lstCabinF = new ArrayList<>();
                    for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                        if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                            continue;
                        }
                        if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                            lstCabinY.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                            lstCabinC.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("F")) {
                            lstCabinF.add(cabinInfoVo);
                        }
                    }
                    flightVo.getLstCabinGroup().add(lstCabinY);
                    flightVo.getLstCabinGroup().add(lstCabinC);
                    flightVo.getLstCabinGroup().add(lstCabinF);
                }*/
                flightVos(flight.flightVos);
            }
            if (flight.flightTransfers != null && flight.flightTransfers.size() > 0) {
                a:
                for (int i = flight.flightTransfers.size() - 1; i >= 0; i --) {
                    BigDecimal moneySum = new BigDecimal(0);
                    for (FlightVo flightVo : flight.flightTransfers.get(i).flightVoList) {
                        BigDecimal money = null;
                        for (CabinInfoVo cabinInfo : flightVo.getListCabinInfo()) {
                            if (cabinInfo.getBaseCabin() != null && !cabinInfo.getBaseCabin().equals("")) {
                                if (cabinInfo.getBaseCabin().equals("Y")) {
                                    if (money == null)
                                        money = cabinInfo.getPrice();
                                    else if (cabinInfo.getPrice().compareTo(money) == -1)
                                        money = cabinInfo.getPrice();
                                }
                            }
                        }
                        if (money == null) {
                            flight.flightTransfers.remove(i);
                            continue a;
                        } else {
                            moneySum = moneySum.add(money);
                        }
                    }
                    if (Long.valueOf(moneySum.toString()) > 0) {
                        flight.flightTransfers.get(i).transferId = IdUtils.simpleUUID();
                        String cabinDesc = null;
                        Long cabinNumber = null;
                        for (FlightVo flightVo : flight.flightTransfers.get(i).flightVoList) {
                            flightVo.setTransferMoney(moneySum);
                            flightVo.setStopCount(flight.flightTransfers.size());
                            flightVo.setStopCount(flight.flightTransfers.get(i).flightVoList.size() - 1);

                            for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                                if (cabinInfoVo.getBaseCabin() != null && !cabinInfoVo.getBaseCabin().equals("")) {
                                    if (cabinInfoVo.getBaseCabin().equals("Y")) {
                                        if (cabinDesc == null && cabinNumber == null) {
                                            if (cabinInfoVo.getCabinLeftDesc().equals("座位充足")) {
                                                cabinDesc = cabinInfoVo.getCabinLeftDesc();
                                            } else {
                                                cabinNumber = Long.valueOf(cabinInfoVo.getCabinLeftDesc());
                                            }
                                        } else {
                                            if (cabinDesc != null) {
                                                if (cabinInfoVo.getCabinLeftDesc().equals("座位充足")) {
                                                    flightVo.setTransferCabinLeft(cabinInfoVo.getCabinLeftDesc());
                                                }
                                            } else if (cabinNumber != null) {
                                                if (cabinInfoVo.getCabinLeftDesc().equals("座位充足")) {
                                                    flightVo.setTransferCabinLeft(String.valueOf(cabinNumber));
                                                } else {
                                                    if (cabinNumber < Long.valueOf(cabinInfoVo.getCabinLeftDesc())) {
                                                        flightVo.setTransferCabinLeft(String.valueOf(cabinNumber));
                                                    } else {
                                                        flightVo.setTransferCabinLeft(cabinInfoVo.getCabinLeftDesc());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            List<CabinInfoVo> lstCabinY = new ArrayList<>();
                            List<CabinInfoVo> lstCabinC = new ArrayList<>();
                            List<CabinInfoVo> lstCabinF = new ArrayList<>();
                            for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                                if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                                    continue;
                                }
                                if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                                    lstCabinY.add(cabinInfoVo);
                                }
                                if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                                    lstCabinC.add(cabinInfoVo);
                                }
                                if (cabinInfoVo.getBaseCabin().equals("F")) {
                                    lstCabinF.add(cabinInfoVo);
                                }
                            }
                            flightVo.getLstCabinGroup().add(lstCabinY);
                            flightVo.getLstCabinGroup().add(lstCabinC);
                            flightVo.getLstCabinGroup().add(lstCabinF);
                        }
                    }
                }
            }
            if (flight.flightVos.size() > 0 && flight.backFlightVos.size() > 0) {
                flightVos(flight.flightVos);
                flightVos(flight.backFlightVos);
                //flightVos(flight.flightVosApp);
                /*for (FlightVo flightVo : flight.flightVos) {
                    List<CabinInfoVo> lstCabinY = new ArrayList<>();
                    List<CabinInfoVo> lstCabinC = new ArrayList<>();
                    List<CabinInfoVo> lstCabinF = new ArrayList<>();
                    for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                        if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                            continue;
                        }
                        if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                            lstCabinY.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                            lstCabinC.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("F")) {
                            lstCabinF.add(cabinInfoVo);
                        }
                    }
                    flightVo.getLstCabinGroup().add(lstCabinY);
                    flightVo.getLstCabinGroup().add(lstCabinC);
                    flightVo.getLstCabinGroup().add(lstCabinF);
                }
                for (FlightVo flightVo : flight.backFlightVos) {
                    List<CabinInfoVo> lstCabinY = new ArrayList<>();
                    List<CabinInfoVo> lstCabinC = new ArrayList<>();
                    List<CabinInfoVo> lstCabinF = new ArrayList<>();
                    for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                        if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                            continue;
                        }
                        if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                            lstCabinY.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                            lstCabinC.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("F")) {
                            lstCabinF.add(cabinInfoVo);
                        }
                    }
                    flightVo.getLstCabinGroup().add(lstCabinY);
                    flightVo.getLstCabinGroup().add(lstCabinC);
                    flightVo.getLstCabinGroup().add(lstCabinF);
                }*/
            }
            /*if (flight.flightVos.size() > 0 && flight.backFlightVos.size() > 0 && flight.flightVosApp.size() > 0) {
                for (FlightVo flightVo : flight.flightVos) {
                    List<CabinInfoVo> lstCabinY = new ArrayList<>();
                    List<CabinInfoVo> lstCabinC = new ArrayList<>();
                    List<CabinInfoVo> lstCabinF = new ArrayList<>();
                    for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                        if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                            continue;
                        }
                        if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                            lstCabinY.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                            lstCabinC.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("F")) {
                            lstCabinF.add(cabinInfoVo);
                        }
                    }
                    flightVo.getLstCabinGroup().add(lstCabinY);
                    flightVo.getLstCabinGroup().add(lstCabinC);
                    flightVo.getLstCabinGroup().add(lstCabinF);
                }
                for (FlightVo flightVo : flight.backFlightVos) {
                    List<CabinInfoVo> lstCabinY = new ArrayList<>();
                    List<CabinInfoVo> lstCabinC = new ArrayList<>();
                    List<CabinInfoVo> lstCabinF = new ArrayList<>();
                    for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                        if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                            continue;
                        }
                        if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                            lstCabinY.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                            lstCabinC.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("F")) {
                            lstCabinF.add(cabinInfoVo);
                        }
                    }
                    flightVo.getLstCabinGroup().add(lstCabinY);
                    flightVo.getLstCabinGroup().add(lstCabinC);
                    flightVo.getLstCabinGroup().add(lstCabinF);
                }
                for (FlightVo flightVo : flight.flightVosApp) {
                    List<CabinInfoVo> lstCabinY = new ArrayList<>();
                    List<CabinInfoVo> lstCabinC = new ArrayList<>();
                    List<CabinInfoVo> lstCabinF = new ArrayList<>();
                    for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                        if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                            continue;
                        }
                        if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                            lstCabinY.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                            lstCabinC.add(cabinInfoVo);
                        }
                        if (cabinInfoVo.getBaseCabin().equals("F")) {
                            lstCabinF.add(cabinInfoVo);
                        }
                    }
                    flightVo.getLstCabinGroup().add(lstCabinY);
                    flightVo.getLstCabinGroup().add(lstCabinC);
                    flightVo.getLstCabinGroup().add(lstCabinF);
                }
            }*/
        }
        return list;
    }

    /**
     * 舱位等级处理
     * @param flightVos
     * @return
     */
    private List<FlightVo> flightVos(List<FlightVo> flightVos) {
        for (FlightVo flightVo : flightVos) {
            List<CabinInfoVo> lstCabinY = new ArrayList<>();
            List<CabinInfoVo> lstCabinC = new ArrayList<>();
            List<CabinInfoVo> lstCabinF = new ArrayList<>();
            for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                    continue;
                }
                if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                    lstCabinY.add(cabinInfoVo);
                }
                if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                    lstCabinC.add(cabinInfoVo);
                }
                if (cabinInfoVo.getBaseCabin().equals("F")) {
                    lstCabinF.add(cabinInfoVo);
                }
            }
            flightVo.getLstCabinGroup().add(lstCabinY);
            flightVo.getLstCabinGroup().add(lstCabinC);
            flightVo.getLstCabinGroup().add(lstCabinF);
        }
        return flightVos;
    }

    /**
     * 创建机票订单
     *
     * @param moRequest
     * @param token
     * @return
     */
    @Override
    public FlightOrderResponse createOrder(MoCreateOrderRequest moRequest, String token) {
        if (token != null && !token.equals(""))
            moRequest.sourceTypeId = "App";
        else
            moRequest.sourceTypeId = "Crm";
        MoCreateOrderResponse response = null;
        FlightOrderResponse orderResponse = new FlightOrderResponse();

        R<Customer> customer;
        try {
            customer = remoteCustomerService.getLoginCustomerByToken(token);
            CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
            customerIdVoApi.setCustomerId(customer.getData().getCustomerId());
            //CustomerIdVoApi customerIdApi = remoteCustomerService.customerIdApi(customerIdVoApi);

            //辅营产品
            List<BigDecimal> additionalList = new ArrayList<>();
            if (moRequest.products != null && moRequest.products.size() > 0) {
                for (AuxiliaryProducts products : moRequest.products) {
                    R<AssistProductApi> productApiR = remoteCustomerService.queryAssistProduct(products.getProductId());
                    BigDecimal insuranceamount = productApiR.getData().getUnderlinePrice();
                    additionalList.add(insuranceamount);
                }
            }
            //金币
            BigDecimal depositSkipPwdAmount = new BigDecimal(0);
            R<Long> longR = remoteCustomerService.queyUserDepositBusinessByToken(token);
            if (longR.getData() != null) {
                depositSkipPwdAmount = new BigDecimal(longR.getData());
            }

            //积分
            R<Long> pntValueR = remoteCustomerService.queyUserCreditsNumByToken(token);
            Long pntValue = 0L;
            if (pntValueR.getData() != null) {
                pntValue = pntValueR.getData();
            }

            CalculationVOApi calculationVOApi = new CalculationVOApi();
            List<BigDecimal> unitPriceList = new ArrayList<>();
            for (MoPassenger moPassenger : moRequest.ListMoPassenger) {
                unitPriceList.add(moPassenger.AgencyFee);  //代理服务费
                unitPriceList.add(moPassenger.AirportTax);  //机建费
                unitPriceList.add(moPassenger.FuelTax);  //燃油费
                unitPriceList.add(moPassenger.TicketAmount);  //票面价
                if (moPassenger.backTicketAmount != null && moPassenger.backTicketAmount.compareTo(BigDecimal.valueOf(0)) != 0)
                    unitPriceList.add(moPassenger.backTicketAmount);
            }
            if (moRequest.iternary != null && moRequest.iternary.getPostWay().equals(1L))
                unitPriceList.add(new BigDecimal(10));
            calculationVOApi.setPrices(unitPriceList);//商品单价集合
            calculationVOApi.setAmount(1);//商品数量
            calculationVOApi.setAdditionalPrices(additionalList);//附加商品单价集合
            calculationVOApi.setAdditionalAmount(1);//附加商品数量
            calculationVOApi.setCouponId(moRequest.couponId);//优惠卷id
            calculationVOApi.setDepositAmount(depositSkipPwdAmount);//用户拥有的金币数量
            calculationVOApi.setUseDeposit(moRequest.useDeposit);//是否使用金币
            if (pntValue != null) {
                calculationVOApi.setPointAmount(Integer.parseInt(pntValue.toString()));//用户拥有的积分数量
            } else {
                calculationVOApi.setPointAmount(0);
            }
            calculationVOApi.setUsePoint(moRequest.usePoint);//是否使用积分
            CalculationDTO calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
            BigDecimal couponAmount = calculationDTO.getPrice();

            BigDecimal payamount = new BigDecimal(moRequest.payamount.toString());
            if (couponAmount.compareTo(payamount) != 0){
                orderResponse.setHasSuccess(false);
                orderResponse.setMsg("支付价格出现变动");
                return orderResponse;
            }
            FlightOutticketLog outticketLog = new FlightOutticketLog();
            int channelType = moRequest.channelType;
            FlightOrderInfo info = new FlightOrderInfo();
            //判断从那个渠道下的订单
            if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达
                orderResponse = saveOrder(moRequest, token, EnumHelper.RequestType.LinkStar.toString());
                outticketLog.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                //乘客信息
                if (!orderResponse.isHasSuccess()) {
                    orderResponse.setOrderId("");
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("订单创建失败！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    return orderResponse;
                }
                outticketLog.setCreateTime(new Date());
                outticketLog.setLoginfo("订单创建成功！");
                outticketLogService.insertFlightOutticketLog(outticketLog);
                response = linkStar._OrderCreate(moRequest);
                info.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                info.setPnr(response.MainOrderID);
                info.setActionCode(response.actionCode);

                //获取订单详细信息
                List<FlightOrderInfoTickets> ticketList = orderInfoTicketsService.selectOrderInfoTicketByOrderId(Long.valueOf(orderResponse.getOrderId()));
                //获取出票渠道信息
                //获取出票渠道主表信息
                FlightChannelRule channelRule = channelRuleService.selectFlightChannelInfo(ticketList.get(0).getAirliner());
                //获取出票渠道详细信息
                FlightInterface flightInterface = interfaceService.selectFlightInterfaceByAirCodeAndType(channelRule.getAirlinerId(), Long.valueOf(channelRule.getPeksourcetype()));
                if (flightInterface.getSourcetype() == Integer.parseInt(FlightOrderConstants.bsp.getValue())) {
                    info.setTicketChannel(FlightOrderConstants.bsp.toString());
                } else {
                    info.setTicketChannel(FlightOrderConstants.b2b.toString());
                }

                //下单成功后需要走运价计算，如果运价计算失败，整个订单都是失败的
                if (response.IsSuccess) {
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("该订单开始在领达预定！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    //查询运价
                    CalculationResponse calculationResponse = linkStar.calculationFreight(response.MainOrderID);
                    if (calculationResponse.isSuccess()) {
                        //PNR结构化信息提取，获取下单后的航司大编
                        MoQueryOrderRequest orderRequest = new MoQueryOrderRequest();
                        orderRequest.OrderID = response.MainOrderID;
                        MoQueryOrderResponse orderResponse1 = linkStar._QueryOrderInfo(orderRequest);
                        String bigPnr = orderResponse1.bigPnr;

                        info.setBigpnr(bigPnr);
                        //总金额 = 票价 + 基建+ 燃油
                        BigDecimal totalPay = new BigDecimal(calculationResponse.getAmount()).add(new BigDecimal(calculationResponse.getFuelTax())).add(new BigDecimal(calculationResponse.getAirportTax()));
                        info.setPayAmount(new BigDecimal(0.1));
                        info.setTicketAmount(totalPay);
                        response.PayAmount = couponAmount;
                        info.setPnrMark("预订成功");
                        info.setPnrstatus(FlightOrderConstants.success.toString());

                        //orderResponse.setOrderId(response.MainOrderID);
                        orderResponse.setHasSuccess(true);
                        orderResponse.setPayAmount(couponAmount);
                        orderResponse.setMsg("预订成功");
                        outticketLog.setCreateTime(new Date());
                        outticketLog.setLoginfo("该订单在领达预定成功，PNR号：" + info.getPnr());
                        outticketLogService.insertFlightOutticketLog(outticketLog);
                    } else {
                        outticketLog.setCreateTime(new Date());
                        outticketLog.setLoginfo("该订单在领达预定失败！");
                        outticketLogService.insertFlightOutticketLog(outticketLog);
                        info.setPnrMark(calculationResponse.getMsg());
                        info.setPnrstatus(FlightOrderConstants.fail.toString());
                        orderResponse.setHasSuccess(false);
                        orderResponse.setMsg("预订失败");
                    }

                } else {
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("该订单在领达预定失败！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    info.setPnrMark(response.ErrorMsg);
                    info.setPnrstatus(FlightOrderConstants.fail.toString());
                    orderResponse.setHasSuccess(false);
                    orderResponse.setMsg(response.ErrorMsg);
                    FlightOrderInfo flightOrderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(orderResponse.getOrderId()));
                    FlightOrderException exception = new FlightOrderException();
                    exception.setPassenger(flightOrderInfo.getCustomerName());
                    FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                    orderInfoTickets.setOrderId(flightOrderInfo.getOrderId());
                    List<FlightOrderInfoTickets> ticketsList = orderInfoTicketsService.selectFlightOrderInfoTicketsList(orderInfoTickets);
                    if (flightOrderInfo.getTripType().equals("ow")) {
                        if (ticketsList.size() > 1) {
                            if (ticketsList.get(1).getTripType().equals("rt") || ticketsList.get(1).getTripType().equals("ot")) {
                                for (int i = 0; i < 2; i++) {
                                    exception.setFlightno(ticketsList.get(i).getFlight());
                                    exception.setFlightinfo(ticketsList.get(i).getOrgAirport() + ticketsList.get(i).getDstAirport());
                                    exception.setDepartureTime(ticketsList.get(i).getDepartureTime());
                                    exception.setArrivalTime(ticketsList.get(i).getArrivalTime());
                                    exception.setOutticketType(EnumHelper.RequestType.LinkStar.toString());
                                    exception.setExceptionInfo(response.ErrorMsg);
                                    exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                                    exception.setStatus("untreated");
                                    exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                                    exception.setOrderType("reserve");
                                    exception.setPnr(flightOrderInfo.getPnr());
                                    flightOrderExceptionService.insertFlightOrderException(exception);
                                }
                            } else {
                                exception.setFlightno(ticketsList.get(0).getFlight());
                                exception.setFlightinfo(ticketsList.get(0).getOrgAirport() + ticketsList.get(0).getDstAirport());
                                exception.setDepartureTime(ticketsList.get(0).getDepartureTime());
                                exception.setArrivalTime(ticketsList.get(0).getArrivalTime());
                                exception.setOutticketType(EnumHelper.RequestType.LinkStar.toString());
                                exception.setExceptionInfo(response.ErrorMsg);
                                exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                                exception.setStatus("untreated");
                                exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                                exception.setOrderType("reserve");
                                exception.setPnr(flightOrderInfo.getPnr());
                                flightOrderExceptionService.insertFlightOrderException(exception);
                            }
                        } else {
                            exception.setFlightno(ticketsList.get(0).getFlight());
                            exception.setFlightinfo(ticketsList.get(0).getOrgAirport() + ticketsList.get(0).getDstAirport());
                            exception.setDepartureTime(ticketsList.get(0).getDepartureTime());
                            exception.setArrivalTime(ticketsList.get(0).getArrivalTime());
                            exception.setOutticketType(EnumHelper.RequestType.LinkStar.toString());
                            exception.setExceptionInfo(response.ErrorMsg);
                            exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                            exception.setStatus("untreated");
                            exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                            exception.setOrderType("reserve");
                            exception.setPnr(flightOrderInfo.getPnr());
                            flightOrderExceptionService.insertFlightOrderException(exception);
                        }
                    } else if (flightOrderInfo.getTripType().equals("rt")) {
                        for (int i = 0; i < 2; i++) {
                            exception.setFlightno(ticketsList.get(i).getFlight());
                            exception.setFlightinfo(ticketsList.get(i).getOrgAirport() + ticketsList.get(i).getDstAirport());
                            exception.setDepartureTime(ticketsList.get(i).getDepartureTime());
                            exception.setArrivalTime(ticketsList.get(i).getArrivalTime());
                            exception.setOutticketType(EnumHelper.RequestType.LinkStar.toString());
                            exception.setExceptionInfo(response.ErrorMsg);
                            exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                            exception.setStatus("untreated");
                            exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                            exception.setOrderType("reserve");
                            exception.setPnr(flightOrderInfo.getPnr());
                            flightOrderExceptionService.insertFlightOrderException(exception);
                        }
                    }
                    return orderResponse;
                }
                orderInfoService.updateFlightOrderInfo(info);

            } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
                response = hangBanGuanJia.orderCreate(moRequest);
            } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
                orderResponse = saveOrder(moRequest, token, EnumHelper.RequestType.G5.toString());
                outticketLog.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                if (!orderResponse.isHasSuccess()) {
                    orderResponse.setOrderId("");
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("订单创建失败！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    return orderResponse;
                }
                outticketLog.setCreateTime(new Date());
                outticketLog.setLoginfo("订单创建成功！");
                outticketLogService.insertFlightOutticketLog(outticketLog);
                response = huaXia._OrderCreate(moRequest);
            } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
                response = ruiLi._OrderCreate(moRequest);
            } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
                orderResponse = saveOrder(moRequest, token, EnumHelper.RequestType.Spring.toString());
                outticketLog.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                if (!orderResponse.isHasSuccess()) {
                    orderResponse.setOrderId("");
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("订单创建失败！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    return orderResponse;
                }
                outticketLog.setCreateTime(new Date());
                outticketLog.setLoginfo("订单创建成功！");
                outticketLogService.insertFlightOutticketLog(outticketLog);
                response = springFlight._OrderCreateNormal(moRequest);
                info.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                info.setTicketChannel(FlightOrderConstants.LinkAirline.toString());
                info.setPayAmount(new BigDecimal(0.1));
                info.setTicketAmount(response.PayAmount);
                if (response.IsSuccess) {
                    info.setPnr(response.MainOrderID);
                    info.setPnrMark("预订成功");
                    info.setPnrstatus(FlightOrderConstants.success.toString());

                    orderResponse.setHasSuccess(true);
                    orderResponse.setPayAmount(couponAmount);
                    orderResponse.setMsg("预订成功");
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("该订单在春秋预定成功，PNR号：" + info.getPnr());
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                } else {
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("该订单在春秋预定失败！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    info.setPnrMark(response.ErrorMsg);
                    info.setPnrstatus(FlightOrderConstants.fail.toString());
                    orderResponse.setHasSuccess(false);
                    orderResponse.setMsg(response.ErrorMsg);
                    FlightOrderInfo flightOrderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(orderResponse.getOrderId()));
                    FlightOrderException exception = new FlightOrderException();
                    exception.setPassenger(flightOrderInfo.getCustomerName());
                    FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                    orderInfoTickets.setOrderId(flightOrderInfo.getOrderId());
                    List<FlightOrderInfoTickets> ticketsList = orderInfoTicketsService.selectFlightOrderInfoTicketsList(orderInfoTickets);
                    if (flightOrderInfo.getTripType().equals("ow")) {
                        if (ticketsList.size() > 1) {
                            if (ticketsList.get(1).getTripType().equals("rt") || ticketsList.get(1).getTripType().equals("ot")) {
                                for (int i = 0; i < 2; i++) {
                                    exception.setFlightno(ticketsList.get(i).getFlight());
                                    exception.setFlightinfo(ticketsList.get(i).getOrgAirport() + ticketsList.get(i).getDstAirport());
                                    exception.setDepartureTime(ticketsList.get(i).getDepartureTime());
                                    exception.setArrivalTime(ticketsList.get(i).getArrivalTime());
                                    exception.setOutticketType(EnumHelper.RequestType.Spring.toString());
                                    exception.setExceptionInfo(response.ErrorMsg);
                                    exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                                    exception.setStatus("untreated");
                                    exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                                    exception.setOrderType("reserve");
                                    exception.setPnr(flightOrderInfo.getPnr());
                                    flightOrderExceptionService.insertFlightOrderException(exception);
                                }
                            } else {
                                exception.setFlightno(ticketsList.get(0).getFlight());
                                exception.setFlightinfo(ticketsList.get(0).getOrgAirport() + ticketsList.get(0).getDstAirport());
                                exception.setDepartureTime(ticketsList.get(0).getDepartureTime());
                                exception.setArrivalTime(ticketsList.get(0).getArrivalTime());
                                exception.setOutticketType(EnumHelper.RequestType.Spring.toString());
                                exception.setExceptionInfo(response.ErrorMsg);
                                exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                                exception.setStatus("untreated");
                                exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                                exception.setOrderType("reserve");
                                exception.setPnr(flightOrderInfo.getPnr());
                                flightOrderExceptionService.insertFlightOrderException(exception);
                            }
                        } else {
                            exception.setFlightno(ticketsList.get(0).getFlight());
                            exception.setFlightinfo(ticketsList.get(0).getOrgAirport() + ticketsList.get(0).getDstAirport());
                            exception.setDepartureTime(ticketsList.get(0).getDepartureTime());
                            exception.setArrivalTime(ticketsList.get(0).getArrivalTime());
                            exception.setOutticketType(EnumHelper.RequestType.Spring.toString());
                            exception.setExceptionInfo(response.ErrorMsg);
                            exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                            exception.setStatus("untreated");
                            exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                            exception.setOrderType("reserve");
                            exception.setPnr(flightOrderInfo.getPnr());
                            flightOrderExceptionService.insertFlightOrderException(exception);
                        }
                    } else if (flightOrderInfo.getTripType().equals("rt")) {
                        for (int i = 0; i < 2; i++) {
                            exception.setFlightno(ticketsList.get(i).getFlight());
                            exception.setFlightinfo(ticketsList.get(i).getOrgAirport() + ticketsList.get(i).getDstAirport());
                            exception.setDepartureTime(ticketsList.get(i).getDepartureTime());
                            exception.setArrivalTime(ticketsList.get(i).getArrivalTime());
                            exception.setOutticketType(EnumHelper.RequestType.Spring.toString());
                            exception.setExceptionInfo(response.ErrorMsg);
                            exception.setSourceWay(flightOrderInfo.getSourceTypeId());
                            exception.setStatus("untreated");
                            exception.setOrderId(String.valueOf(flightOrderInfo.getOrderId()));
                            exception.setOrderType("reserve");
                            exception.setPnr(flightOrderInfo.getPnr());
                            flightOrderExceptionService.insertFlightOrderException(exception);
                        }
                    }
                    return orderResponse;
                }
                orderInfoService.updateFlightOrderInfo(info);
            } else if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
                //TODO 去哪儿待确定，暂未完成，以后完善
                orderResponse = saveOrder(moRequest, token, EnumHelper.RequestType.Qunar.toString());
                outticketLog.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                if (!orderResponse.isHasSuccess()) {
                    orderResponse.setOrderId("");
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("订单创建失败！");
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                    return orderResponse;
                }
                outticketLog.setCreateTime(new Date());
                outticketLog.setLoginfo("订单创建成功！");
                outticketLogService.insertFlightOutticketLog(outticketLog);
                //发送请求
                response = qunar._OrderCreate(moRequest);
                info.setOrderId(Long.valueOf(orderResponse.getOrderId()));
                info.setTicketChannel(FlightOrderConstants.LinkAirline.toString());
                info.setPayAmount(new BigDecimal(0.1));
                info.setTicketAmount(response.PayAmount);
                if (response.IsSuccess) {
                    info.setPnr(response.MainOrderID);
                    info.setPnrMark("预订成功");
                    info.setPnrstatus(FlightOrderConstants.success.toString());

                    orderResponse.setHasSuccess(true);
                    orderResponse.setPayAmount(couponAmount);
                    orderResponse.setMsg("预订成功");
                    outticketLog.setCreateTime(new Date());
                    outticketLog.setLoginfo("该订单在去哪儿预定成功，PNR号：" + info.getPnr());
                    outticketLogService.insertFlightOutticketLog(outticketLog);
                }
            }
            orderResponse = createOrderResponse(response, Long.valueOf(orderResponse.getOrderId()));
            if (orderResponse.isHasSuccess()) {
                String orderType = "购买机票";
                String orderSourceDesc = "渠道" + moRequest.channelType + "航段" + moRequest.TripType;
                redisService.setCacheObject("flight" + customer.getData().getCustomerId() + "o" + orderResponse.getOrderId(), JSON.toJSON(orderResponse), 60 * 25L, TimeUnit.SECONDS);
                if ((pntValue != null && pntValue.longValue() > 0L) || (moRequest.couponId != null && moRequest.couponId > 0) || (longR.getData() != null && longR.getData().longValue() > 0L)) {
                    BigDecimal decimal = new BigDecimal(0);
                    if (longR.getData() != null){
                        decimal = new BigDecimal(longR.getData());
                    }
                    remoteCustomerService.spend(customer.getData().getCustomerId(), pntValue, orderType, Long.valueOf(orderResponse.getOrderId()), orderSourceDesc, moRequest.couponId, decimal, 1L);
                }
            }
        } catch (Exception e) {
            orderResponse.setMsg("系统异常");
            e.printStackTrace();
            orderResponse.setHasSuccess(false);
        }
        return orderResponse;
    }

    //保存机票订单（CRM）
    @Override
    public FlightOrderResponse createOrderCRM(MoCreateOrderRequest moRequest, Long customerId) {
        moRequest.sourceTypeId = "Crm";
        FlightOrderResponse response = new FlightOrderResponse();
        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
        customerIdVoApi.setCustomerId(customerId);
        CustomerIdVoApi customerIdApi = remoteCustomerService.customerIdApi(customerIdVoApi);

        //辅营产品
        List<BigDecimal> additionalList = new ArrayList<>();
        if (moRequest.products != null && moRequest.products.size() > 0) {
            for (AuxiliaryProducts products : moRequest.products) {
                R<AssistProductApi> productApiR = remoteCustomerService.queryAssistProduct(products.getProductId());
                if (customerIdApi != null) {
                    if (customerIdApi.getLevel().equals("1")) {
                        BigDecimal insuranceamount = productApiR.getData().getSalePrice();
                        additionalList.add(insuranceamount);
                    } else {
                        BigDecimal insuranceamount = productApiR.getData().getMemberPrice();
                        additionalList.add(insuranceamount);
                    }
                }

            }
        }
        //金币
        BigDecimal depositSkipPwdAmount = new BigDecimal(0);
        R<Long> longR = remoteCustomerService.selectAvailableGoldByCustomerId(customerId);
        if (longR.getData() != null) {
            depositSkipPwdAmount = new BigDecimal(longR.getData());
        }

        //积分
        R<Long> pntValueR = remoteCustomerService.queyUserCreditsNumByCustomerId(customerId);
        Long pntValue = 0L;
        if (pntValueR.getData() != null) {
            pntValue = pntValueR.getData();
        }

        CalculationVOApi calculationVOApi = new CalculationVOApi();
        List<BigDecimal> unitPriceList = new ArrayList<>();
        for (MoPassenger moPassenger : moRequest.ListMoPassenger) {
            unitPriceList.add(moPassenger.AgencyFee);  //代理服务费
            unitPriceList.add(moPassenger.AirportTax);  //机建费
            unitPriceList.add(moPassenger.FuelTax);  //燃油费
            unitPriceList.add(moPassenger.TicketAmount);  //票面价
            if (moPassenger.backTicketAmount != null && moPassenger.backTicketAmount.compareTo(BigDecimal.valueOf(0)) != 0)
                unitPriceList.add(moPassenger.backTicketAmount);
        }
        if (moRequest.iternary != null && moRequest.iternary.getPostWay().equals(1L))
            unitPriceList.add(new BigDecimal(10));
        calculationVOApi.setPrices(unitPriceList);//商品单价集合
        calculationVOApi.setAmount(1);//商品数量
        calculationVOApi.setAdditionalPrices(additionalList);//附加商品单价集合
        calculationVOApi.setAdditionalAmount(1);//附加商品数量
        calculationVOApi.setCouponId(0L);//优惠卷id
        calculationVOApi.setDepositAmount(depositSkipPwdAmount);//用户拥有的金币数量
        calculationVOApi.setUseDeposit(moRequest.useDeposit);//是否使用金币
        if (pntValue != null) {
            calculationVOApi.setPointAmount(Integer.parseInt(pntValue.toString()));//用户拥有的积分数量
        } else {
            calculationVOApi.setPointAmount(0);
        }
        calculationVOApi.setUsePoint(false);//是否使用积分
        CalculationDTO calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
        BigDecimal couponAmount = calculationDTO.getPrice();

        BigDecimal payamount = new BigDecimal(moRequest.payamount.toString());
        if (couponAmount.compareTo(payamount) != 0){
            response.setHasSuccess(false);
            response.setMsg("支付价格出现变动");
            return response;
        }
        String changType = "";
        switch (String.valueOf(moRequest.channelType)) {
            case "7":
                changType = EnumHelper.RequestType.Spring.toString();
                break;
            case "14":
                changType = EnumHelper.RequestType.LinkStar.toString();
                break;
            case "16":
                changType = EnumHelper.RequestType.Qunar.toString();
                break;
            case "17":
                changType = EnumHelper.RequestType.DR.toString();
                break;
            case "18":
                changType = EnumHelper.RequestType.G5.toString();
                break;
            case "19":
                changType = EnumHelper.RequestType.HangBanGuanJia.toString();
                break;
        }
        response = saveOrderCRM(moRequest, customerId, changType);
        response.setPayAmount(payamount);
        FlightOutticketLog outticketLog = new FlightOutticketLog();
        outticketLog.setOrderId(Long.valueOf(response.getOrderId()));
        outticketLog.setLoginfo("该订单在领达预定成功，PNR号：" + response.getMsg());
        outticketLog.setCreateTime(new Date());
        outticketLogService.insertFlightOutticketLog(outticketLog);
        return response;
    }

    //生成预定命令（CRM）
    @Override
    public FlightOrderResponse createPNR(MoCreateOrderRequest moRequest) {
        FlightOrderResponse orderResponse = new FlightOrderResponse();
        MoCreateOrderResponse response = null;
        try {
            int channelType = moRequest.channelType;
            if (channelType == EnumHelper.RequestType.LinkStar.getValue()) {
                response = linkStar._OrderCreate(moRequest);
                if (response.IsSuccess) {
                    //查询运价
                    CalculationResponse calculationResponse = linkStar.calculationFreight(response.MainOrderID);
                    if (calculationResponse.isSuccess()) {
                        //PNR结构化信息提取，获取下单后的航司大编
                        MoQueryOrderRequest orderRequest = new MoQueryOrderRequest();
                        orderRequest.OrderID = response.MainOrderID;
                        MoQueryOrderResponse orderResponse1 = linkStar._QueryOrderInfo(orderRequest);
                        String bigPnr = orderResponse1.bigPnr;
                        //总金额 = 票价 + 基建+ 燃油
                        BigDecimal totalPay = new BigDecimal(calculationResponse.getAmount()).add(new BigDecimal(calculationResponse.getFuelTax())).add(new BigDecimal(calculationResponse.getAirportTax()));
                        orderResponse.setOrderId(response.MainOrderID);
                        orderResponse.setMsg(bigPnr);
                        orderResponse.setHasSuccess(true);
                        orderResponse.setActionCode(response.actionCode);
                        long count = moRequest.ListMoPassenger.stream().map(MoPassenger::getPassengerType).distinct().count();
                        if (count != 1) {
                            BigDecimal totalAmount = new BigDecimal(0);
                            for (MoPassenger moPassenger : moRequest.ListMoPassenger) {
                                if (moPassenger.PassengerType == 1) {
                                    totalAmount.add(totalPay);
                                } else if (moPassenger.PassengerType == 2 || moPassenger.PassengerType == 3) {
                                    totalAmount.add(moPassenger.TicketAmount).add(moPassenger.AirportTax).add(moPassenger.FuelTax);
                                }
                            }
                            orderResponse.setTotalPay(totalAmount);
                        } else {
                            orderResponse.setTotalPay(totalPay.multiply(new BigDecimal(moRequest.ListMoPassenger.size())));
                        }
                        XElement xElement = linkStar.airResRetCompleteRQ(response.MainOrderID);
                        XElement referenceInfo = xElement.element("BookingReferenceInfo");
                        JSONObject xml = XML.toJSONObject(String.valueOf(referenceInfo));
                        String jsonStr = xml.toString();
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(jsonStr);
                        Map<String, Object> ticketItemInfoMap = new HashMap<>();
                        //循环转换
                        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                            ticketItemInfoMap.put(entry.getKey(), entry.getValue());
                        }
                        String bookingReferenceInfo = ticketItemInfoMap.get("BookingReferenceInfo").toString();
                        orderResponse.setOriginalText(bookingReferenceInfo);
                    } else {
                        orderResponse.setOrderId(response.MainOrderID);
                        orderResponse.setMsg("运价查询失败！");
                        orderResponse.setHasSuccess(false);
                    }
                } else {
                    orderResponse.setHasSuccess(false);
                    orderResponse.setMsg(response.ErrorMsg);
                    orderResponse.setOrderId("");
                }
            } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
                response = springFlight._OrderCreateNormal(moRequest);
                if (response.IsSuccess) {
                    orderResponse.setOrderId(response.MainOrderID);
                    orderResponse.setHasSuccess(true);
                    orderResponse.setTotalPay(response.PayAmount);
                } else {
                    orderResponse.setHasSuccess(false);
                    orderResponse.setMsg(response.ErrorMsg);
                    orderResponse.setOrderId("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderResponse;
    }

    @Override
    public MoCancelOrderResponse cancelPNR(String pnr)
    {
        return linkStar._changeCancelOrder(pnr);
    }

    @Override
    public MoQueryOrderResponse searchOrderInfo(MoQueryOrderRequest orderRequest) {
        int channelType = orderRequest.channelType;
        MoQueryOrderResponse orderResponse = null;
        try {
            if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
                orderResponse = qunar._QueryOrderInfo(orderRequest);
            } else if (channelType == EnumHelper.RequestType.LinkStar.getValue()) {
                orderResponse = linkStar._QueryOrderInfo(orderRequest);
            } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
                orderResponse = hangBanGuanJia.queryOrderInfo(orderRequest);
            } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
                orderResponse = springFlight._QueryOrderInfo(orderRequest);
            } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
                orderResponse = ruiLi._QueryOrderInfo(orderRequest);
            } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
                orderResponse = huaXia._QueryOrderInfo(orderRequest);
            }

            //查询结果
            if (orderResponse.IsSuccess) {
                FlightOrderInfo info = orderInfoService.selectFlightOrderInfo(orderRequest.OrderID);
                info.setPnrstatus(orderResponse.OrderStatusMsg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return orderResponse;
    }

    @Override
    public MoCancelOrderResponse cancelOrder(MoCancelOrderRequest moRequest) {
        MoCancelOrderResponse response = null;
        FlightOrderInfo flightOrderInfo = orderInfoService.selectFlightOrderInfo(moRequest.ListOrderItem.OrderID); //获取订单主表信息
        FlightOutticketLog outticketLog = new FlightOutticketLog();
        int channelType = 0;
        if (flightOrderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (flightOrderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (flightOrderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            channelType = EnumHelper.RequestType.G5.getValue();
        } else if (flightOrderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            channelType = EnumHelper.RequestType.DR.getValue();
        } else if (flightOrderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (flightOrderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            channelType = EnumHelper.RequestType.Qunar.getValue();
        }

        //判断从那个渠道下的订单
        if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达
            outticketLog.setOrderId(Long.valueOf(moRequest.ListOrderItem.OrderID));
            outticketLog.setLoginfo("该订单准备在领达取消预订！");
            outticketLog.setCreateTime(new Date());
            outticketLogService.insertFlightOutticketLog(outticketLog);
            response = linkStar._CancelOrder(moRequest);
            boolean isSuccess = response.ListOrderItem.get(0).IsSuccess;
            //如果接口取消订单成功，则修改订单状态
            if (isSuccess) {
                //修改订单状态
                flightOrderInfo.setOrderStatusId(FlightOrderConstants.cancel.toString());
                flightOrderInfo.setActionCode("XX");
                flightOrderInfo.setStatus(FlightOrderConstants.cancelled.getValue());
                flightOrderInfo.setGuestPymtStsId(FlightOrderConstants.cancelled.getValue());
                //执行保存
                orderInfoService.updateFlightOrderInfo(flightOrderInfo);
                outticketLog.setLoginfo("该订单在领达取消预订成功！");
                outticketLog.setCreateTime(new Date());
                outticketLogService.insertFlightOutticketLog(outticketLog);
            } else {
                outticketLog.setLoginfo("该订单在领达取消预订失败！");
                outticketLog.setCreateTime(new Date());
                outticketLogService.insertFlightOutticketLog(outticketLog);
            }
        } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
            response = hangBanGuanJia.cancelOrder(moRequest);
        } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
            response = huaXia._CancelOrder(moRequest);
        } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
            response = ruiLi._CancelOrder(moRequest);
        } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
            response = springFlight._CancelOrder(moRequest);
        } else if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
            // TODO 去哪没有取消订单接口
            //response = qunar._CancelOrder(moRequest);
        }

        return response;
    }

    @Override
    public MoOrderPayResponse payOrder(MoOrderPayRequest moRequest) {

        MoOrderPayResponse response = new MoOrderPayResponse();

        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfo(moRequest.OrderID); //获取订单主表信息

        int channelType = 0;

        if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            channelType = EnumHelper.RequestType.G5.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            channelType = EnumHelper.RequestType.DR.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            channelType = EnumHelper.RequestType.Qunar.getValue();
        }

        //判断从那个渠道下的订单
        if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达
            response = linkStar._OrderPay(moRequest);
        } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
            response = hangBanGuanJia.orderPay(moRequest);
        } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
            response = huaXia._OrderPay(moRequest);
        } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
            response = ruiLi._OrderPay(moRequest);
        } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
            response = springFlight._OrderPay(moRequest);
        } else if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
            response = qunar._OrderPay(moRequest);
        }

        if (response.IsSuccess) {
            if (moRequest.employee != null) {
                FlightOrderException exception = new FlightOrderException();
                exception.setStatus("processed");
                exception.setOpreator(moRequest.employee.getEmployeeId());
                exception.setOpreateTime(new Date());
                flightOrderExceptionService.updateFlightOrderExceptionByOrderId(exception);
            }

            List<FlightOrderInfoTickets> infoTicketsList = orderInfoTicketsService.selectFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId());
            BigDecimal returnMoney = new BigDecimal(0);
            for (FlightOrderInfoTickets item : infoTicketsList) {
                if (item.getReturnCash() != null)
                    returnMoney.add(item.getReturnCash());
                List<FlightOrderAssist> orderAssists = flightOrderAssistService.queryFlightOrderAssist(item.getOrderInfoTicketsId());
                if (orderAssists != null && orderAssists.size() > 0) {
                    for (FlightOrderAssist orderAssist : orderAssists) {
                        if (orderAssist.getInsType() != null && orderAssist.getInsType().equals("insurance")) {
                            if (orderInfo.getTripType().equals("ow")) {
                                if (infoTicketsList.size() > 1) {
                                    if (infoTicketsList.get(1).getTripType().equals("ow")) {
                                        ProductVoApi product = new ProductVoApi();
                                        product.id = orderAssist.getAssistProductId();
                                        product.customerId = orderInfo.getCustomerId();
                                        product.orderNum = String.valueOf(orderInfo.getOrderId() + item.getOrderInfoTicketsId());
                                        product.paymentChannel = orderInfo.getPayType();
                                        product.relation = "01";
                                        //证件类型
                                        product.insuredIdType = EmHelper.CertificateType.ID_CARD.getValue();
                                        if (item.getIdTypeId() == EnumHelper.PsgerIDType.军官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.士官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.义务兵证.getValue()) {
                                            product.insuredIdType = EmHelper.CertificateType.MILITARY_ID.getValue();
                                        } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.出生医学证明.getValue()) {
                                            product.insuredIdType = EmHelper.CertificateType.BIRTH_CERTIFICATE.getValue();
                                        } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.护照.getValue()) {
                                            product.insuredIdType = EmHelper.CertificateType.PASSPORT.getValue();
                                        } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.港澳通行证.getValue()) {
                                            product.insuredIdType = EmHelper.CertificateType.MTPFHKAMR.getValue();
                                        } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.户口簿.getValue()) {
                                            product.insuredIdType = EmHelper.CertificateType.ACCOUNT_BOOK.getValue();
                                        }
                                        product.flightNo = item.getFlight();
                                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        String departureTime = dateFormat.format(item.getDepartureTime());
                                        String[] departure = departureTime.split(" ");
                                        product.flightDate = departureTime;
                                        product.flightTime = departure[1];
                                        String arrivalTime = dateFormat.format(item.getArrivalTime());
                                        String[] arrival = arrivalTime.split(" ");
                                        product.arriveTime = arrival[1];
                                        product.insuredName = item.getGuestName();
                                        product.insuredId = item.getGuestIdno();
                                        product.insuredPhone = item.getGuestMobile();
                                        String guestBirthday = dateFormat.format(item.getGuestBirthday());
                                        product.beInsuredBirthday = guestBirthday.split(" ")[0];
                                        String ticketNo = item.getTicketNo();
                                        String[] split = ticketNo.split("-");
                                        product.ticketNo = split[0] + split[1];
                                        product.flightIndex = "1";
                                        product.depCity = item.getOrgAirport();
                                        product.arrCity = item.getDstAirport();
                                        product.insuranceType = 5;
                                        product.orderSource = BusinessTypeConstants.flight.getValue();
                                        InsuranceReturnVoApi recordBack = remoteCustomerService.insertInsuranceRecordBack(product);
                                        if (recordBack != null) {
                                            if (recordBack.isSuccess()) {
                                                orderAssist.setStatus("normal");
                                                flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                            } else {
                                                orderAssist.setStatus("fail");
                                                flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                            }
                                        } else {
                                            orderAssist.setStatus("fail");
                                            flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                        }
                                    } else {
                                        for (int i = 0; i < 2; i++) {
                                            ProductVoApi product = new ProductVoApi();
                                            product.id = orderAssist.getAssistProductId();
                                            product.customerId = orderInfo.getCustomerId();
                                            if (i == 0) {
                                                product.orderNum = orderInfo.getOrderId() + item.getOrderInfoTicketsId() + "ow";
                                                product.flightIndex = "1";
                                            } else {
                                                product.orderNum = orderInfo.getOrderId() + item.getOrderInfoTicketsId() + "ot";
                                                product.flightIndex = "2";
                                            }
                                            product.paymentChannel = orderInfo.getPayType();
                                            product.relation = "01";
                                            //证件类型
                                            product.insuredIdType = EmHelper.CertificateType.ID_CARD.getValue();
                                            if (item.getIdTypeId() == EnumHelper.PsgerIDType.军官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.士官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.义务兵证.getValue()) {
                                                product.insuredIdType = EmHelper.CertificateType.MILITARY_ID.getValue();
                                            } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.出生医学证明.getValue()) {
                                                product.insuredIdType = EmHelper.CertificateType.BIRTH_CERTIFICATE.getValue();
                                            } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.护照.getValue()) {
                                                product.insuredIdType = EmHelper.CertificateType.PASSPORT.getValue();
                                            } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.港澳通行证.getValue()) {
                                                product.insuredIdType = EmHelper.CertificateType.MTPFHKAMR.getValue();
                                            } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.户口簿.getValue()) {
                                                product.insuredIdType = EmHelper.CertificateType.ACCOUNT_BOOK.getValue();
                                            }
                                            product.flightNo = item.getFlight();
                                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                            String departureTime = dateFormat.format(item.getDepartureTime());
                                            String[] departure = departureTime.split(" ");
                                            product.flightDate = departureTime;
                                            product.flightTime = departure[1];
                                            String arrivalTime = dateFormat.format(item.getArrivalTime());
                                            String[] arrival = arrivalTime.split(" ");
                                            product.arriveTime = arrival[1];
                                            product.insuredName = item.getGuestName();
                                            product.insuredId = item.getGuestIdno();
                                            product.insuredPhone = item.getGuestMobile();
                                            String guestBirthday = dateFormat.format(item.getGuestBirthday());
                                            product.beInsuredBirthday = guestBirthday.split(" ")[0];
                                            String ticketNo = item.getTicketNo();
                                            String[] split = ticketNo.split("-");
                                            product.ticketNo = split[0] + split[1];
                                            product.depCity = item.getOrgAirport();
                                            product.arrCity = item.getDstAirport();
                                            product.insuranceType = 5;
                                            product.orderSource = BusinessTypeConstants.flight.getValue();
                                            InsuranceReturnVoApi recordBack = remoteCustomerService.insertInsuranceRecordBack(product);
                                            if (recordBack != null) {
                                                if (recordBack.isSuccess()) {
                                                    orderAssist.setStatus("normal");
                                                    flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                                } else {
                                                    orderAssist.setStatus("fail");
                                                    flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                                }
                                            } else {
                                                orderAssist.setStatus("fail");
                                                flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                            }
                                        }
                                    }
                                } else {
                                    ProductVoApi product = new ProductVoApi();
                                    product.id = orderAssist.getAssistProductId();
                                    product.customerId = orderInfo.getCustomerId();
                                    product.orderNum = String.valueOf(orderInfo.getOrderId() + item.getOrderInfoTicketsId());
                                    product.paymentChannel = orderInfo.getPayType();
                                    product.relation = "01";
                                    //证件类型
                                    product.insuredIdType = EmHelper.CertificateType.ID_CARD.getValue();
                                    if (item.getIdTypeId() == EnumHelper.PsgerIDType.军官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.士官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.义务兵证.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.MILITARY_ID.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.出生医学证明.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.BIRTH_CERTIFICATE.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.护照.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.PASSPORT.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.港澳通行证.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.MTPFHKAMR.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.户口簿.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.ACCOUNT_BOOK.getValue();
                                    }
                                    product.flightNo = item.getFlight();
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                    String departureTime = dateFormat.format(item.getDepartureTime());
                                    String[] departure = departureTime.split(" ");
                                    product.flightDate = departureTime;
                                    product.flightTime = departure[1];
                                    String arrivalTime = dateFormat.format(item.getArrivalTime());
                                    String[] arrival = arrivalTime.split(" ");
                                    product.arriveTime = arrival[1];
                                    product.insuredName = item.getGuestName();
                                    product.insuredId = item.getGuestIdno();
                                    product.insuredPhone = item.getGuestMobile();
                                    String guestBirthday = dateFormat.format(item.getGuestBirthday());
                                    product.beInsuredBirthday = guestBirthday.split(" ")[0];
                                    String ticketNo = item.getTicketNo();
                                    String[] split = ticketNo.split("-");
                                    product.ticketNo = split[0] + split[1];
                                    product.flightIndex = "1";
                                    product.depCity = item.getOrgAirport();
                                    product.arrCity = item.getDstAirport();
                                    product.insuranceType = 5;
                                    product.orderSource = BusinessTypeConstants.flight.getValue();
                                    InsuranceReturnVoApi recordBack = remoteCustomerService.insertInsuranceRecordBack(product);
                                    if (recordBack != null) {
                                        if (recordBack.isSuccess()) {
                                            orderAssist.setStatus("normal");
                                            flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                        } else {
                                            orderAssist.setStatus("fail");
                                            flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                        }
                                    } else {
                                        orderAssist.setStatus("fail");
                                        flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                    }
                                }
                            } else if (orderInfo.getTripType().equals("rt")) {
                                for (int i = 0; i < 2; i++) {
                                    ProductVoApi product = new ProductVoApi();
                                    product.id = orderAssist.getAssistProductId();
                                    product.customerId = orderInfo.getCustomerId();
                                    if (i == 0) {
                                        product.orderNum = orderInfo.getOrderId() + item.getOrderInfoTicketsId() + "ow";
                                        product.flightIndex = "1";
                                    } else {
                                        product.orderNum = orderInfo.getOrderId() + item.getOrderInfoTicketsId() + "rt";
                                        product.flightIndex = "2";
                                    }
                                    product.paymentChannel = orderInfo.getPayType();
                                    product.relation = "01";
                                    //证件类型
                                    product.insuredIdType = EmHelper.CertificateType.ID_CARD.getValue();
                                    if (item.getIdTypeId() == EnumHelper.PsgerIDType.军官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.士官证.getValue() || item.getIdTypeId() == EnumHelper.PsgerIDType.义务兵证.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.MILITARY_ID.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.出生医学证明.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.BIRTH_CERTIFICATE.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.护照.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.PASSPORT.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.港澳通行证.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.MTPFHKAMR.getValue();
                                    } else if (item.getIdTypeId() == EnumHelper.PsgerIDType.户口簿.getValue()) {
                                        product.insuredIdType = EmHelper.CertificateType.ACCOUNT_BOOK.getValue();
                                    }
                                    product.flightNo = item.getFlight();
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                    String departureTime = dateFormat.format(item.getDepartureTime());
                                    String[] departure = departureTime.split(" ");
                                    product.flightDate = departureTime;
                                    product.flightTime = departure[1];
                                    String arrivalTime = dateFormat.format(item.getArrivalTime());
                                    String[] arrival = arrivalTime.split(" ");
                                    product.arriveTime = arrival[1];
                                    product.insuredName = item.getGuestName();
                                    product.insuredId = item.getGuestIdno();
                                    product.insuredPhone = item.getGuestMobile();
                                    String guestBirthday = dateFormat.format(item.getGuestBirthday());
                                    product.beInsuredBirthday = guestBirthday.split(" ")[0];
                                    String ticketNo = item.getTicketNo();
                                    String[] split = ticketNo.split("-");
                                    product.ticketNo = split[0] + split[1];
                                    product.depCity = item.getOrgAirport();
                                    product.arrCity = item.getDstAirport();
                                    product.insuranceType = 5;
                                    product.orderSource = BusinessTypeConstants.flight.getValue();
                                    InsuranceReturnVoApi recordBack = remoteCustomerService.insertInsuranceRecordBack(product);
                                    if (recordBack!=null)
                                    {
                                        if (recordBack.isSuccess()) {
                                            orderAssist.setStatus("normal");
                                            flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                        } else {
                                            orderAssist.setStatus("fail");
                                            flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                        }
                                    }else
                                    {
                                        orderAssist.setStatus("fail");
                                        flightOrderAssistService.updateFlightOrderAssist(orderAssist);
                                    }
                                }
                            }
                        } else if (orderAssist.getInsType() != null && orderAssist.getInsType().equals("conpon")) {
                            R<AssistProductApi> productApiR = remoteCustomerService.queryAssistProduct(orderAssist.getAssistProductId());
                            if (productApiR.getCode() == 200 && productApiR.getData() != null) {
                                R<Coupon> couponR = remoteCustomerService.couponById(productApiR.getData().getProductTypeid());
                                CustomerRightdetail customerRightdetai = new CustomerRightdetail();
                                customerRightdetai.setCustomerId(orderInfo.getCustomerId());
                                customerRightdetai.setRightdetailId(couponR.getData().getCouponId());
                                customerRightdetai.setRightdetailName(couponR.getData().getCouponName());
                                customerRightdetai.setCouponMoney(couponR.getData().getCouponPrice());
                                customerRightdetai.setValidDate(new Date());
                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(new Date());
                                calendar.add(Calendar.YEAR, 1);
                                customerRightdetai.setInvalidDate(calendar.getTime());
                                customerRightdetai.setCreateEmployeeId(1L);
                                customerRightdetai.setCreateTime(new Date());
                                customerRightdetai.setRightdetailSource(CustomerConstants.rightSourcePack.getValue());
                                customerRightdetai.setRightdetailType(CustomerConstants.rightTypeCoupon.getValue());
                                customerRightdetai.setRightdetailTypeid(couponR.getData().getCouponId());
                                customerRightdetai.setRightdetailState(CustomerConstants.unexecuted.getValue());
                                remoteCustomerService.addCustomerRightdetail(customerRightdetai);
                            }
                        }
                    }
                }
            }
            if (returnMoney.compareTo(new BigDecimal(0)) != 0) {
                DepositBusinessApi business = new DepositBusinessApi();
                business.setOperationtime(new Date());
                business.setRemark("机票返现添加，订单号：" + orderInfo.getOrderId());
                business.setState(EmHelper.Audit.NotReviewed.getValue());
                business.setBusinessType(BusinessTypeConstants.flight.getValue());
                business.setOperapersonid(1L);
                business.setOrdersourceid(orderInfo.getSourceTypeId());
                business.setCustomerId(orderInfo.getCustomerId());
                business.setDetailamount(returnMoney);
                business.setChangetype(1L);
                business.setCreateTime(new Date());
                business.setLockState("false");
                business.setOrderId(orderInfo.getOrderId());
                business.setDrawState("true");
                customerService.addReserveMoney(business);
            }
        }

        return response;
    }


    @Override
    public FightStopResVo searchStopFightInfo(FightStopReqVo vo) {
        FightStopResVo flightInfoVo = null;
        String key = vo.getCode() + vo.getFlightNo() + vo.getDate();
        String redisKey = FLIGHT + key;
        //判断缓存中是否存在
        Object cacheObject = redisService.getCacheObject(redisKey);

        if (cacheObject != null) {
            String string = JSON.toJSONString(cacheObject);
            String jsonStr = JSON.parse(string).toString();
            flightInfoVo = JSON.parseObject(jsonStr, FightStopResVo.class);
            return flightInfoVo;
        } else {

            flightInfoVo = linkStar.searchStopFightInfo(vo);
            if (flightInfoVo != null && flightInfoVo.getCode() == null || flightInfoVo.getCode() == ""
                    && flightInfoVo.getMsg() == null || flightInfoVo.getMsg() == "") {
                //放入缓存(10分钟)
                redisService.setCacheObject(redisKey, JSON.toJSONString(flightInfoVo), 10L, TimeUnit.MINUTES);
            }

            return flightInfoVo;
        }
    }

    /**
     * 退票
     *
     * @param moRequest
     * @return
     */
    @Override
    public MoOrderRefundResponse orderRefund(MoOrderRefundRequest moRequest, HttpServletRequest servletRequest) throws Exception {
        MoOrderRefundResponse response = new MoOrderRefundResponse();
        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfo(moRequest.OrderID); //获取订单主表信息

        if (orderInfo.getDepositAmount() != null && orderInfo.getDepositAmount().compareTo(new BigDecimal(0)) > 0){
            String token = servletRequest.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            Customer customer = remoteCustomerService.getLoginCustomerByToken(token).getData();
            if (employee == null && customer == null){
                throw new Exception("登陆已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票退票");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            if (employee != null)
                depositBusiness.setOperatorId(employee.getEmployeeId());
            else
                depositBusiness.setOperatorId(1L);
            depositBusiness.setOrdersourceid(moRequest.type);
            depositBusiness.setCustomerId(orderInfo.getCustomerId());
            depositBusiness.setDetailamount(orderInfo.getDepositAmount());
            depositBusiness.setChangetype(1l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(orderInfo.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }
        }

        int channelType = 0;
        if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            channelType = EnumHelper.RequestType.G5.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            channelType = EnumHelper.RequestType.DR.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            channelType = EnumHelper.RequestType.Qunar.getValue();
        }

        try {
            //判断从那个渠道下的订单
            if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达

                //先判断机票是否被使用
                TicketInfoResponse ticketInfo = linkStar.ticketInfo(orderInfo.getPnr());
                if (!ticketInfo.isSuccess()) {
                    response.ErrorMsg = ticketInfo.getMsg();
                    response.ErrorCode = ticketInfo.getCode();
                    response.IsSuccess = false;
                    return response;
                }

                //先判断这个订单出票渠道是b2b还是bsp,如果是bsp的则可以申请退票，其他转人工

                List<FlightOrderInfoTickets> ticketList = orderInfoTicketsService.selectOrderInfoTicketByOrderId(Long.valueOf(moRequest.OrderID));
                //获取出票渠道信息
                //获取出票渠道主表信息
                FlightChannelRule channelRule = channelRuleService.selectFlightChannelInfo(ticketList.get(0).getAirliner());
                //获取出票渠道详细信息
                FlightInterface flightInterface = interfaceService.selectFlightInterfaceByAirCodeAndType(channelRule.getAirlinerId(), Long.valueOf(channelRule.getPeksourcetype()));
                if (flightInterface.getSourcetype() != Integer.parseInt(FlightOrderConstants.bsp.getValue())) {
                    response.ErrorMsg = "此订单不支持自动退票，请转人工处理！";
                    response.IsSuccess = false;
                    return response;
                }

                if (orderInfo.getTripType().equals(FlightOrderConstants.ow.toString())) {
                    if (moRequest.ListMoPassenger.size() == ticketList.size()) {
                        //执行取消订单 操作
                        MoCancelOrderRequest request = new MoCancelOrderRequest();
                        MoOrderItem item = new MoOrderItem();
                        item.OrderID = moRequest.OrderID;
                        request.ListOrderItem = item;
                        MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                        boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                        //如果接口取消订单成功，则修改订单状态
                        FlightOrderInfo info = orderInfoService.selectFlightOrderInfo(moRequest.OrderID);
                        if (isSuccess) {
                            //修改订单状态
                            info.setStatus(FlightOrderConstants.refundProgress.toString());
                            info.setOperationTime(new Date());
                            info.setActionCode("XX");
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundProgress.getValue());
                        } else {
                            //修改订单状态
                            info.setStatus(FlightOrderConstants.refundTicketFail.toString());
                            info.setOperationTime(new Date());
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketFail.getValue());
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                        //执行退票
                        response = linkStar._OrderRefund(moRequest);
                        if (response.IsSuccess) {
                            //修改订单状态
                            info.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                            info.setOperationTime(new Date());
                            info.setActionCode("XX");
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketStatus_success.toString());
                        } else {
                            //修改订单状态
                            info.setStatus(FlightOrderConstants.refundTicketFail.toString());
                            info.setOperationTime(new Date());
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketFail.getValue());
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                    } else {
                        List<MoPassenger> ps = new ArrayList<>();
                        for (FlightOrderInfoTickets tickets : ticketList) {
                            moRequest.ListMoPassenger.forEach(item -> {
                                if (tickets.getTicketNo().equals(item.TicketNo)) {
                                    MoPassenger passenger = new MoPassenger();
                                    if (tickets.getGuestType().equals(EnumHelper.PassengerType.成人.toString())) {
                                        passenger.PassengerType = EnumHelper.PassengerType.成人.getValue();
                                    } else if (tickets.getGuestType().equals(EnumHelper.PassengerType.儿童.toString())) {
                                        passenger.PassengerType = EnumHelper.PassengerType.儿童.getValue();
                                    } else if (tickets.getGuestType().equals(EnumHelper.PassengerType.婴儿.toString())) {
                                        passenger.PassengerType = EnumHelper.PassengerType.婴儿.getValue();
                                    }

                                    passenger.IDType = Math.toIntExact(tickets.getIdTypeId());
                                    passenger.PassengerName = tickets.getGuestName();
                                    passenger.IDNO = tickets.getGuestIdno();

                                    ps.add(passenger);
                                }
                            });
                        }
                        XElement xElement = linkStar.separatePNR(ps, orderInfo.getPnr());
                        String pnr = xElement.element("AirReservation").element("BookingReferenceID").getAttributeValue("ID");
                        //执行取消订单 操作
                        MoCancelOrderRequest request = new MoCancelOrderRequest();
                        MoOrderItem item = new MoOrderItem();
                        item.OrderID = pnr;
                        request.ListOrderItem = item;
                        MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                        boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                        //如果接口取消订单成功，则修改订单状态
                        List<String> ticketNo = new ArrayList<>();
                        if (isSuccess) {
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("1");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundProgress.getValue());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                                ticketNo.add(passenger.TicketNo);
                            }
                        } else {
                            //执行保存
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("1");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketFail.getValue());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                                ticketNo.add(passenger.TicketNo);
                            }
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                        //执行退票
                        response = linkStar._OrderRefunds(Long.valueOf(moRequest.OrderID), ticketNo);
                        if (response.IsSuccess) {
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("2");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                            }
                        } else {
                            //执行保存
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("1");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketFail.getValue());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                                ticketNo.add(passenger.TicketNo);
                            }
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                    }
                } else if (orderInfo.getTripType().equals(FlightOrderConstants.rt.toString())) {
                    if ((moRequest.ListMoPassenger.size() * 2) == ticketList.size()) {
                        //执行取消订单 操作
                        MoCancelOrderRequest request = new MoCancelOrderRequest();
                        MoOrderItem item = new MoOrderItem();
                        item.OrderID = moRequest.OrderID;
                        request.ListOrderItem = item;
                        MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                        boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                        //如果接口取消订单成功，则修改订单状态
                        FlightOrderInfo info = orderInfoService.selectFlightOrderInfo(moRequest.OrderID);
                        if (isSuccess) {
                            //修改订单状态
                            info.setOrderStatusId(FlightOrderConstants.refundProgress.toString());
                            info.setOperationTime(new Date());
                            info.setActionCode("XX");
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundProgress.getValue());
                        } else {
                            //修改订单状态
                            info.setOrderStatusId(FlightOrderConstants.refundTicketFail.toString());
                            info.setOperationTime(new Date());
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketFail.getValue());
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                        //执行退票
                        response = linkStar._OrderRefund(moRequest);
                        if (response.IsSuccess) {
                            //修改订单状态
                            info.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                            info.setOperationTime(new Date());
                            info.setActionCode("XX");
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketStatus_success.toString());
                        } else {
                            //修改订单状态
                            info.setOrderStatusId(FlightOrderConstants.refundTicketFail.toString());
                            info.setOperationTime(new Date());
                            //执行保存
                            orderInfoService.updateFlightOrderInfo(info);
                            orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketFail.getValue());
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                    } else {
                        List<MoPassenger> ps = new ArrayList<>();
                        moRequest.ListMoPassenger.forEach(item -> {
                            List<FlightOrderInfoTickets> ticketsList = orderInfoTicketsService.getFlightOrderInfoByTicketNoList(item.TicketNo);
                            MoPassenger passenger = new MoPassenger();
                            if (ticketsList.get(0).getGuestType().equals(EnumHelper.PassengerType.成人.toString())) {
                                passenger.PassengerType = EnumHelper.PassengerType.成人.getValue();
                            } else if (ticketsList.get(0).getGuestType().equals(EnumHelper.PassengerType.儿童.toString())) {
                                passenger.PassengerType = EnumHelper.PassengerType.儿童.getValue();
                            } else if (ticketsList.get(0).getGuestType().equals(EnumHelper.PassengerType.婴儿.toString())) {
                                passenger.PassengerType = EnumHelper.PassengerType.婴儿.getValue();
                            }

                            passenger.IDType = Math.toIntExact(ticketsList.get(0).getIdTypeId());
                            passenger.PassengerName = ticketsList.get(0).getGuestName();
                            passenger.IDNO = ticketsList.get(0).getGuestIdno();

                            ps.add(passenger);
                        });
                        XElement xElement = linkStar.separatePNR(ps, orderInfo.getPnr());
                        String pnr = xElement.element("AirReservation").element("BookingReferenceID").getAttributeValue("ID");
                        //执行取消订单 操作
                        MoCancelOrderRequest request = new MoCancelOrderRequest();
                        MoOrderItem item = new MoOrderItem();
                        item.OrderID = pnr;
                        request.ListOrderItem = item;
                        MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                        boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                        //如果接口取消订单成功，则修改订单状态
                        List<String> ticketNo = new ArrayList<>();
                        if (isSuccess) {
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("1");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundProgress.getValue());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                                ticketNo.add(passenger.TicketNo);
                            }
                        } else {
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("1");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketFail.getValue());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                                ticketNo.add(passenger.TicketNo);
                            }
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                        //执行退票
                        response = linkStar._OrderRefunds(Long.valueOf(moRequest.OrderID), ticketNo);
                        if (response.IsSuccess) {
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("2");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                            }
                        } else {
                            for (MoPassenger passenger : moRequest.ListMoPassenger) {
                                FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                                flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                                flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                                flightOrderInfoTickets.setGuestStatus("1");
                                flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketFail.getValue());
                                orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                                ticketNo.add(passenger.TicketNo);
                            }
                            response.IsSuccess = false;
                            response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                            response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                            return response;
                        }
                    }
                }
                FinanceOrderRefundment refundment = new FinanceOrderRefundment();
                refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.flight.getValue()));
                refundment.setCustomerId(orderInfo.getCustomerId());
                refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
                //TODO 测试阶段，手续费为0，后期完善手续费
                /*BigDecimal payAmount = orderInfo.getPayAmount();
                BigDecimal subtract = payAmount.subtract(new BigDecimal(20));*/
                refundment.setRefundmentAmount(orderInfo.getPayAmount());
                refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
                refundment.setOrderId(String.valueOf(orderInfo.getOrderId()));
                refundment.setApplyTime(new Date());
                if (orderInfo.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
                    refundment.setPaymentTypeId("2");
                } else if (orderInfo.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
                    refundment.setPaymentTypeId("1");
                }
                refundment.setSerialnumber(orderInfo.getBillNo());
                remoteCustomerService.add(refundment);
                } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
                    response = hangBanGuanJia.orderRefund(moRequest);
                } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
                    response = huaXia._OrderRefund(moRequest);
                } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
                    response = ruiLi._OrderRefund(moRequest);
                } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
                    response = springFlight._OrderRefund(moRequest);
                } else if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
                    response = qunar._OrderRefund(moRequest);
                }
        } catch (IOException e) {
            e.printStackTrace();
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            response.ErrorMsg = e.getMessage();
        }

        return response;
    }

    //CRM退票
    @Override
    public MoOrderRefundResponse orderRefundCRM(FlightOrderChange orderChange) throws Exception {
        MoOrderRefundResponse response = new MoOrderRefundResponse();
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        MoOrderRefundRequest moRequest = new MoOrderRefundRequest();
        orderChange.setChangeOrderId(snowflakeUtils.nextId() + "-T"); //退票标识主键
        orderChange.setIsdealing("1");
        orderChange.setAddTime(DateUtils.getNowDate()); //退废申请时间
        orderChange.setChangeType(FlightOrderChangeConstants.refund.getValue());
        orderChange.setChangeFee(orderChange.getChangeFee());
        orderChangeService.insertFlightOrderChange(orderChange);
        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfo(String.valueOf(orderChange.getOrderId())); //获取订单主表信息
        orderChange.getTicketNo().forEach(item -> {
            MoPassenger passenger = new MoPassenger();
            passenger.TicketNo = item;
            moRequest.ListMoPassenger.add(passenger);
            List<FlightOrderInfoTickets> orderInfoTickets = orderInfoTicketsService.getFlightOrderInfoByTicketNoList(item);
            if (orderInfo.getTripType().equals(FlightOrderConstants.ow.toString())) {
                FlightOrderChangeTickets orderChangeTickets = new FlightOrderChangeTickets();
                orderChangeTickets.setChangeTicketId(snowflakeUtils.nextId());
                orderChangeTickets.setOrderId(Long.valueOf(orderChange.getOrderId()));
                orderChangeTickets.setChangeOrderId(orderChange.getChangeOrderId());
                orderChangeTickets.setFlight(orderInfoTickets.get(0).getFlight());
                orderChangeTickets.setAirliner(orderInfoTickets.get(0).getAirliner());
                orderChangeTickets.setCustomerId(orderInfo.getCustomerId());
                orderChangeTickets.setDepartureTime(orderInfoTickets.get(0).getDepartureTime());
                orderChangeTickets.setIdTypeId(orderInfoTickets.get(0).getIdTypeId());
                orderChangeTickets.setGuestName(orderInfoTickets.get(0).getGuestName());
                orderChangeTickets.setTicketPrice(orderInfoTickets.get(0).getTicketPrice());
                orderChangeTickets.setCabin(orderInfoTickets.get(0).getCabin());
                orderChangeTickets.setArrivalTime(orderInfoTickets.get(0).getArrivalTime());
                orderChangeTickets.setGuestType(orderInfoTickets.get(0).getGuestType());
                orderChangeTickets.setGuestBirthday(orderInfoTickets.get(0).getGuestBirthday());
                orderChangeTickets.setGuestIdno(orderInfoTickets.get(0).getGuestIdno());
                orderChangeTickets.setOldTicketNo(orderInfoTickets.get(0).getTicketNo());
                orderChangeTickets.setPlaneStyle(orderInfoTickets.get(0).getFlightType());
                orderChangeTickets.setDepTerm(orderInfoTickets.get(0).getDepTerm());
                orderChangeTickets.setArrTerm(orderInfoTickets.get(0).getArrTerm());
                orderChangeTickets.setPnr(orderInfo.getPnr());
                orderChangeTickets.setBigPnr(orderInfo.getBigpnr());
                orderChangeTickets.setDeparture(orderInfoTickets.get(0).getDeparture());
                orderChangeTickets.setArrival(orderInfoTickets.get(0).getArrival());
                orderChangeTickets.setOrgAirport(orderInfoTickets.get(0).getOrgAirport());
                orderChangeTickets.setDstAirport(orderInfoTickets.get(0).getDstAirport());
                orderChangeTickets.setGuestMobile(orderInfoTickets.get(0).getGuestMobile());
                orderChangeTickets.setActionCode("XX");
                changeTicketsService.insertFlightOrderChangeTickets(orderChangeTickets);
            } else if (orderInfo.getTripType().equals(FlightOrderConstants.rt.toString())) {
                orderInfoTickets.forEach(items -> {
                    FlightOrderChangeTickets orderChangeTickets = new FlightOrderChangeTickets();
                    orderChangeTickets.setChangeTicketId(snowflakeUtils.nextId());
                    orderChangeTickets.setOrderId(orderInfo.getOrderId());
                    orderChangeTickets.setChangeOrderId(orderChange.getChangeOrderId());
                    orderChangeTickets.setFlight(items.getFlight());
                    orderChangeTickets.setAirliner(items.getAirliner());
                    orderChangeTickets.setCustomerId(orderInfo.getCustomerId());
                    orderChangeTickets.setDepartureTime(items.getDepartureTime());
                    orderChangeTickets.setIdTypeId(items.getIdTypeId());
                    orderChangeTickets.setGuestName(items.getGuestName());
                    orderChangeTickets.setTicketPrice(items.getTicketPrice());
                    orderChangeTickets.setCabin(items.getCabin());
                    orderChangeTickets.setArrivalTime(items.getArrivalTime());
                    orderChangeTickets.setGuestType(items.getGuestType());
                    orderChangeTickets.setGuestBirthday(items.getGuestBirthday());
                    orderChangeTickets.setGuestIdno(items.getGuestIdno());
                    orderChangeTickets.setOldTicketNo(items.getTicketNo());
                    orderChangeTickets.setPlaneStyle(items.getFlightType());
                    orderChangeTickets.setDepTerm(items.getDepTerm());
                    orderChangeTickets.setArrTerm(items.getArrTerm());
                    orderChangeTickets.setPnr(orderInfo.getPnr());
                    orderChangeTickets.setBigPnr(orderInfo.getBigpnr());
                    orderChangeTickets.setDeparture(items.getDeparture());
                    orderChangeTickets.setArrival(items.getArrival());
                    orderChangeTickets.setOrgAirport(items.getOrgAirport());
                    orderChangeTickets.setDstAirport(items.getDstAirport());
                    orderChangeTickets.setGuestMobile(items.getGuestMobile());
                    orderChangeTickets.setActionCode("XX");
                    changeTicketsService.insertFlightOrderChangeTickets(orderChangeTickets);
                });
            }
        });

        int channelType = 0;
        if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            channelType = EnumHelper.RequestType.G5.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            channelType = EnumHelper.RequestType.DR.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            channelType = EnumHelper.RequestType.Qunar.getValue();
        }

        //判断从那个渠道下的订单
        if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达
            //先判断机票是否被使用
            TicketInfoResponse ticketInfo = linkStar.ticketInfo(orderInfo.getPnr());
            if (!ticketInfo.isSuccess()) {
                response.ErrorMsg = ticketInfo.getMsg();
                response.ErrorCode = ticketInfo.getCode();
                response.IsSuccess = false;
                return response;
            }

            //先判断这个订单出票渠道是b2b还是bsp,如果是bsp的则可以申请退票，其他转人工
            moRequest.OrderID = String.valueOf(orderInfo.getOrderId());

            List<FlightOrderInfoTickets> ticketList = orderInfoTicketsService.selectOrderInfoTicketByOrderId(Long.valueOf(moRequest.OrderID));
            //获取出票渠道信息
            //获取出票渠道主表信息
            FlightChannelRule channelRule = channelRuleService.selectFlightChannelInfo(ticketList.get(0).getAirliner());
            //获取出票渠道详细信息
            FlightInterface flightInterface = interfaceService.selectFlightInterfaceByAirCodeAndType(channelRule.getAirlinerId(), Long.valueOf(channelRule.getPeksourcetype()));
            if (flightInterface.getSourcetype() != Integer.parseInt(FlightOrderConstants.bsp.getValue())) {
                response.ErrorMsg = "此订单不支持自动退票，请转人工处理！";
                response.IsSuccess = false;
                return response;
            }
            if (orderInfo.getTripType().equals(FlightOrderConstants.ow.toString())) {
                if (moRequest.ListMoPassenger.size() == ticketList.size()) {
                    //执行取消订单 操作
                    MoCancelOrderRequest request = new MoCancelOrderRequest();
                    MoOrderItem item = new MoOrderItem();
                    item.OrderID = moRequest.OrderID;
                    request.ListOrderItem = item;
                    MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                    boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                    //如果接口取消订单成功，则修改订单状态
                    FlightOrderInfo info = orderInfoService.selectFlightOrderInfo(moRequest.OrderID);
                    if (isSuccess) {
                        //修改订单状态
                        info.setStatus(FlightOrderConstants.refundProgress.toString());
                        info.setOperationTime(new Date());
                        info.setActionCode("XX");
                        //执行保存
                        orderInfoService.updateFlightOrderInfo(info);
                        orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundProgress.getValue());
                    } else {
                        response.IsSuccess = false;
                        response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                        response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                        return response;
                    }
                    //执行退票
                    response = linkStar._OrderRefundCRM(moRequest);
                    if (response.IsSuccess) {
                        //修改订单状态
                        info.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                        info.setOperationTime(new Date());
                        info.setActionCode("XX");
                        //执行保存
                        orderInfoService.updateFlightOrderInfo(info);
                        orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketStatus_success.getValue());
                    }
                } else {
                    List<MoPassenger> ps = new ArrayList<>();
                    for (FlightOrderInfoTickets tickets : ticketList) {
                        MoPassenger passenger = new MoPassenger();
                        if (tickets.getGuestType().equals(EnumHelper.PassengerType.成人.toString())) {
                            passenger.PassengerType = EnumHelper.PassengerType.成人.getValue();
                        } else if (tickets.getGuestType().equals(EnumHelper.PassengerType.儿童.toString())) {
                            passenger.PassengerType = EnumHelper.PassengerType.儿童.getValue();
                        } else if (tickets.getGuestType().equals(EnumHelper.PassengerType.婴儿.toString())) {
                            passenger.PassengerType = EnumHelper.PassengerType.婴儿.getValue();
                        }

                        passenger.IDType = Math.toIntExact(tickets.getIdTypeId());
                        passenger.PassengerName = tickets.getGuestName();
                        passenger.IDNO = tickets.getGuestIdno();

                        ps.add(passenger);
                    }
                    XElement xElement = linkStar.separatePNR(ps, orderInfo.getPnr());
                    String pnr = xElement.element("AirReservation").element("BookingReferenceID").getAttributeValue("ID");
                    //执行取消订单 操作
                    MoCancelOrderRequest request = new MoCancelOrderRequest();
                    MoOrderItem item = new MoOrderItem();
                    item.OrderID = pnr;
                    request.ListOrderItem = item;
                    MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                    boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                    //如果接口取消订单成功，则修改订单状态
                    List<String> ticketNo = new ArrayList<>();
                    if (isSuccess) {
                        for (MoPassenger passenger : moRequest.ListMoPassenger) {
                            FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                            flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                            flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                            flightOrderInfoTickets.setGuestStatus("1");
                            flightOrderInfoTickets.setStatus(FlightOrderConstants.refundProgress.getValue());
                            orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                            ticketNo.add(passenger.TicketNo);
                        }
                    } else {
                        response.IsSuccess = false;
                        response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                        response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                        return response;
                    }
                    //执行退票
                    response = linkStar._OrderRefundsCRM(ticketNo);
                    if (response.IsSuccess) {
                        for (MoPassenger passenger : moRequest.ListMoPassenger) {
                            FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                            flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                            flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                            flightOrderInfoTickets.setGuestStatus("2");
                            flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketStatus_success.getValue());
                            orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                        }
                    }
                }
            } else if (orderInfo.getTripType().equals(FlightOrderConstants.rt.toString())) {
                if ((moRequest.ListMoPassenger.size() * 2) == ticketList.size()) {
                    //执行取消订单 操作
                    MoCancelOrderRequest request = new MoCancelOrderRequest();
                    MoOrderItem item = new MoOrderItem();
                    item.OrderID = moRequest.OrderID;
                    request.ListOrderItem = item;
                    MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                    boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                    //如果接口取消订单成功，则修改订单状态
                    FlightOrderInfo info = orderInfoService.selectFlightOrderInfo(moRequest.OrderID);
                    if (isSuccess) {
                        //修改订单状态
                        info.setStatus(FlightOrderConstants.refundProgress.toString());
                        info.setOperationTime(new Date());
                        info.setActionCode("XX");
                        //执行保存
                        orderInfoService.updateFlightOrderInfo(info);
                        orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundProgress.getValue());
                    } else {
                        response.IsSuccess = false;
                        response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                        response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                        return response;
                    }
                    //执行退票
                    response = linkStar._OrderRefundCRM(moRequest);
                    if (response.IsSuccess) {
                        //修改订单状态
                        info.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                        info.setOperationTime(new Date());
                        info.setActionCode("XX");
                        //执行保存
                        orderInfoService.updateFlightOrderInfo(info);
                        orderInfoTicketsService.updateFlightOrderInfoTicketsByOrderId(orderInfo.getOrderId(), FlightOrderConstants.refundTicketStatus_success.getValue());
                    }
                } else {
                    List<MoPassenger> ps = new ArrayList<>();
                    moRequest.ListMoPassenger.forEach(item -> {
                        List<FlightOrderInfoTickets> ticketsList = orderInfoTicketsService.getFlightOrderInfoByTicketNoList(item.TicketNo);
                        MoPassenger passenger = new MoPassenger();
                        if (ticketsList.get(0).getGuestType().equals(EnumHelper.PassengerType.成人.toString())) {
                            passenger.PassengerType = EnumHelper.PassengerType.成人.getValue();
                        } else if (ticketsList.get(0).getGuestType().equals(EnumHelper.PassengerType.儿童.toString())) {
                            passenger.PassengerType = EnumHelper.PassengerType.儿童.getValue();
                        } else if (ticketsList.get(0).getGuestType().equals(EnumHelper.PassengerType.婴儿.toString())) {
                            passenger.PassengerType = EnumHelper.PassengerType.婴儿.getValue();
                        }

                        passenger.IDType = Math.toIntExact(ticketsList.get(0).getIdTypeId());
                        passenger.PassengerName = ticketsList.get(0).getGuestName();
                        passenger.IDNO = ticketsList.get(0).getGuestIdno();

                        ps.add(passenger);
                    });
                    XElement xElement = linkStar.separatePNR(ps, orderInfo.getPnr());
                    String pnr = xElement.element("AirReservation").element("BookingReferenceID").getAttributeValue("ID");
                    //执行取消订单 操作
                    MoCancelOrderRequest request = new MoCancelOrderRequest();
                    MoOrderItem item = new MoOrderItem();
                    item.OrderID = pnr;
                    request.ListOrderItem = item;
                    MoCancelOrderResponse orderResponse = linkStar._CancelOrder(request);

                    boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                    //如果接口取消订单成功，则修改订单状态
                    List<String> ticketNo = new ArrayList<>();
                    if (isSuccess) {
                        for (MoPassenger passenger : moRequest.ListMoPassenger) {
                            FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                            flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                            flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                            flightOrderInfoTickets.setGuestStatus("1");
                            flightOrderInfoTickets.setStatus(FlightOrderConstants.refundProgress.getValue());
                            orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                            ticketNo.add(passenger.TicketNo);
                        }
                    } else {
                        response.IsSuccess = false;
                        response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                        response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                        return response;
                    }
                    //执行退票
                    response = linkStar._OrderRefundsCRM(ticketNo);
                    if (response.IsSuccess) {
                        for (MoPassenger passenger : moRequest.ListMoPassenger) {
                            FlightOrderInfoTickets flightOrderInfoTickets = new FlightOrderInfoTickets();
                            flightOrderInfoTickets.setOrderId(Long.valueOf(moRequest.OrderID));
                            flightOrderInfoTickets.setTicketNo(passenger.TicketNo);
                            flightOrderInfoTickets.setGuestStatus("2");
                            flightOrderInfoTickets.setStatus(FlightOrderConstants.refundTicketStatus_success.getValue());
                            orderInfoTicketsService.updateFlightOrderInfoTicket(flightOrderInfoTickets);
                        }
                    }
                }
            }
        }
        FinanceOrderRefundment refundment = new FinanceOrderRefundment();
        refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.flight.getValue()));
        refundment.setCustomerId(orderInfo.getCustomerId());
        refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
        BigDecimal payAmount = orderInfo.getPayAmount();
        BigDecimal subtract = payAmount.subtract(orderChange.getChangeFee());
        refundment.setRefundmentAmount(subtract);
        refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
        refundment.setOrderId(String.valueOf(orderInfo.getOrderId()));
        refundment.setApplyTime(new Date());
        if (orderInfo.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
            refundment.setPaymentTypeId("2");
        } else if (orderInfo.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
            refundment.setPaymentTypeId("1");
        }
        refundment.setSerialnumber(orderInfo.getBillNo());
        remoteCustomerService.add(refundment);
        /*if (response.IsSuccess) {

            FlightOrderCashInfo flightOrderCashInfo = flightOrderCashInfoMapper.selectFlightOrderCashInfo(Long.valueOf(orderChange.getOrderId()));
            //退款方式
            //原路返回
            if (orderChange.getRefundMethod().equals(FlightOrderConstants.backtrack.getValue())){
                if (flightOrderCashInfo != null){
                    //易宝信用卡退款
                    if (flightOrderCashInfo.getCollectType().equals(BusinessTypeConstants.BankCredit.getValue())){
                        Map<String, String> map = new HashMap<>();
                        map.put("jsjOrderId", flightOrderCashInfo.getOrderId().toString());
                        map.put("bankTrxId", flightOrderCashInfo.getTransactionId());
                        map.put("moneyAmout", flightOrderCashInfo.getActualAmount().toString());
                        map.put("payType", flightOrderCashInfo.getBusinessType());
                        YeeBaoResultApi yeeBaoResultApi = remotePayService.bankCreditRefund(map);
                        if (!yeeBaoResultApi.getCode().equals("1")){
                            throw new Exception("退款失败" + yeeBaoResultApi.getCode());
                        }
                    }
                    //易宝借记卡退款
                    else if (flightOrderCashInfo.getCollectType().equals(BusinessTypeConstants.BankDebit.getValue())){
                        Map<String, String> map = new HashMap<>();
                        map.put("jsjOrderId", flightOrderCashInfo.getOrderId().toString());
                        map.put("bankTrxId", flightOrderCashInfo.getTransactionId());
                        map.put("moneyAmout", flightOrderCashInfo.getActualAmount().toString());
                        map.put("payType", flightOrderCashInfo.getBusinessType());
                        YeeBaoResultApi yeeBaoResultApi = remotePayService.bankDebitRefund(map);
                        if (!yeeBaoResultApi.getCode().equals("1")){
                            throw new Exception("退款失败" + yeeBaoResultApi.getCode());
                        }
                    }
                    //-
                    //银联二维码退款
                    else if (flightOrderCashInfo.getCollectType().equals(BusinessTypeConstants.UnionPayQRCode.getValue())){
                        Map<String, String> map = new HashMap<>();
                        map.put("refundAmount", flightOrderCashInfo.getActualAmount().toString());
                        map.put("billNo", flightOrderCashInfo.getTransactionId());
                        map.put("notifyUrl", "http://106.38.39.137:8080/flight/callback/unionPayQRCodeRefund");
                        UnionPayQRCodeResponseApi unionPayQRCodeResponseApi = remotePayService.qrCodeRefund(map);
                        if (!unionPayQRCodeResponseApi.getErrCode().equals("SUCCESS")){
                            throw new Exception("退款失败" + unionPayQRCodeResponseApi.getErrMsg());
                        }
                    }
                    //
                    else {
                        throw new Exception("无法识别的退款方式");
                    }
                }
                else {
                    throw new Exception("订单已完成退款");
                }
            }
            //预留款
            else if (orderChange.getRefundMethod().equals(FlightOrderConstants.reserveMoney.getValue())){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();

                CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
                customerIdVoApi.setCustomerName(orderChange.getCardholder());
                CustomerIdVoApi tmpCustomerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);

                if (tmpCustomerIdVoApi.getCustomerId() != null && tmpCustomerIdVoApi.getCustomerId() != 0){
                    DepositBusinessApi depositBusiness = new DepositBusinessApi();
                    depositBusiness.setOperationtime(format.parse(format.format(date)));
                    depositBusiness.setRemark("机票订单退款");
                    depositBusiness.setState(EmHelper.Audit.NotReviewed.getValue());
                    depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
                    depositBusiness.setOperatorId(orderChange.getEmployeeId());
                    depositBusiness.setOrdersourceid(flightOrderCashInfo.getBusinessType());
                    depositBusiness.setCustomerId(tmpCustomerIdVoApi.getCustomerId());
                    depositBusiness.setDetailamount(flightOrderCashInfo.getActualAmount());
                    depositBusiness.setChangetype(1l);
                    depositBusiness.setOrderId(flightOrderCashInfo.getOrderId());
                    int refund = remoteCustomerService.refund(depositBusiness);
                    if (refund <= 0){
                        throw new Exception("预留款记录添加失败");
                    }
                }
                else {
                    throw new Exception("持卡人为非会员，无法存入预留款");
                }
            }
            else {
                throw new Exception("无法识别的退款方式");
            }*/
        orderChange.setChangeStatus(FlightOrderConstants.refundTicketStatus_success.getValue()); //退票状态
        orderChange.setRefundNumber(response.refundNumber);
        orderChangeService.updateFlightOrderChange(orderChange);
        return response;
    }

    //改签退票
    @Override
    public MoOrderRefundResponse changeOrderRefund(MoOrderRefundRequest moRequest, HttpServletRequest request) throws Exception {
        MoOrderRefundResponse response = new MoOrderRefundResponse();
        FlightOrderChange orderChange = orderChangeService.selectFlightOrderChangeById(moRequest.OrderID);
        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfo(String.valueOf(orderChange.getOrderId())); //获取订单主表信息

        if (orderInfo.getDepositAmount() != null){
            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登陆已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票改签退票");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(moRequest.type);
            depositBusiness.setCustomerId(orderInfo.getCustomerId());
            depositBusiness.setDetailamount(orderInfo.getDepositAmount());
            depositBusiness.setChangetype(1l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(orderInfo.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款失败");
            }
        }

        FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
        infoTickets.setOrderId(orderInfo.getOrderId());
        List<FlightOrderInfoTickets> orderInfoTickets = orderInfoTicketsService.selectFlightOrderInfoTicketsList(infoTickets);
        FlightOrderChangeTickets changeTickets = new FlightOrderChangeTickets();
        changeTickets.setChangeOrderId(orderChange.getChangeOrderId());
        List<FlightOrderChangeTickets> ticketsList = changeTicketsService.selectFlightOrderChangeTicketsList(changeTickets);
        int channelType = 0;
        if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            channelType = EnumHelper.RequestType.G5.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            channelType = EnumHelper.RequestType.DR.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            channelType = EnumHelper.RequestType.Qunar.getValue();
        }
        try {
            if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达
                FlightOrderChangeTickets tickets = changeTicketsService.queryOrderChangeTickets(moRequest.ticketNo);
                TicketInfoResponse ticketInfo = linkStar.ticketInfo(tickets.getPnr());
                if (!ticketInfo.isSuccess()) {
                    response.ErrorMsg = ticketInfo.getMsg();
                    response.ErrorCode = ticketInfo.getCode();
                    response.IsSuccess = false;
                    return response;
                }
                //先判断这个订单出票渠道是b2b还是bsp,如果是bsp的则可以申请退票，其他转人工
                //获取出票渠道信息
                FlightChannelRule channelRule = channelRuleService.selectFlightChannelInfo(tickets.getAirliner());
                //获取出票渠道详细信息
                FlightInterface flightInterface = interfaceService.selectFlightInterfaceByAirCodeAndType(channelRule.getAirlinerId(), Long.valueOf(channelRule.getPeksourcetype()));
                if (flightInterface.getSourcetype() != Integer.parseInt(FlightOrderConstants.bsp.getValue())) {
                    response.ErrorMsg = "此订单不支持自动退票，请转人工处理！";
                    response.IsSuccess = false;
                    return response;
                }
                MoCancelOrderResponse orderResponse = linkStar._changeCancelOrder(tickets.getPnr());
                boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
                if (!isSuccess) {
                    response.IsSuccess = false;
                    response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                    response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                    return response;
                }
                //执行退票
                response = linkStar._changeOrderRefund(moRequest);
                FinanceOrderRefundment refundment = new FinanceOrderRefundment();
                refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.flight.getValue()));
                refundment.setCustomerId(orderInfo.getCustomerId());
                refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
                //TODO 测试阶段，手续费为0，后期完善手续费
                for (FlightOrderChangeTickets orderChangeTickets : ticketsList) {
                    if (orderChangeTickets.getTicketNo().equals(moRequest.ticketNo)) {
                        if (response.IsSuccess) {
                            orderChangeTickets.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                            changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                        }
                        BigDecimal multiply = orderInfo.getPayAmount().multiply(new BigDecimal(orderInfoTickets.size()));
                        if (orderChangeTickets.getChangeFee() != null) {
                            //BigDecimal add = multiply.add(orderChangeTickets.getChangeFee()).subtract(new BigDecimal(20));
                            BigDecimal add = multiply.add(orderChangeTickets.getChangeFee());
                            refundment.setRefundmentAmount(add);
                        }
                    }
                }
                //refundment.setRefundmentAmount(orderInfo.getPayAmount());
                refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
                refundment.setOrderId(String.valueOf(orderInfo.getOrderId()));
                refundment.setApplyTime(new Date());
                if (orderInfo.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
                    refundment.setPaymentTypeId("2");
                } else if (orderInfo.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
                    refundment.setPaymentTypeId("1");
                }
                refundment.setSerialnumber(orderInfo.getBillNo());
                remoteCustomerService.add(refundment);
            } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
                response = hangBanGuanJia.orderRefund(moRequest);
            } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
                response = huaXia._OrderRefund(moRequest);
            } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
                response = ruiLi._OrderRefund(moRequest);
            } else if (channelType == EnumHelper.RequestType.Spring.getValue()) {
                response = springFlight._OrderRefund(moRequest);
            } else if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
                response = qunar._OrderRefund(moRequest);
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            response.ErrorMsg = e.getMessage();
        }
        return response;
    }

    //CRM改签退票
    @Override
    public MoOrderRefundResponse changeOrderRefundCRM(FlightOrderChange orderChange) {
        MoOrderRefundResponse response = new MoOrderRefundResponse();
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        MoOrderRefundRequest moRequest = new MoOrderRefundRequest();
        moRequest.OrderID = orderChange.getChangeOrderId();
        moRequest.ticketNo = orderChange.getTicketNo().get(0);
        FlightOrderChange orderChanges = orderChangeService.selectFlightOrderChangeById(moRequest.OrderID);
        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfo(String.valueOf(orderChanges.getOrderId())); //获取订单主表信息
        FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
        infoTickets.setOrderId(orderInfo.getOrderId());
        List<FlightOrderInfoTickets> orderInfoTickets = orderInfoTicketsService.selectFlightOrderInfoTicketsList(infoTickets);
        FlightOrderChangeTickets changeTickets = new FlightOrderChangeTickets();
        changeTickets.setChangeOrderId(orderChange.getChangeOrderId());
        List<FlightOrderChangeTickets> ticketsList = changeTicketsService.selectFlightOrderChangeTicketsList(changeTickets);
        orderChange.setChangeOrderId(snowflakeUtils.nextId() + "-T"); //退票标识主键
        orderChange.setIsdealing("1");
        orderChange.setAddTime(DateUtils.getNowDate()); //退废申请时间
        orderChange.setChangeType(FlightOrderChangeConstants.refund.getValue());
        orderChange.setOldChangeOrderId(orderChanges.getChangeOrderId());
        orderChange.setChangeFee(orderChange.getChangeFee());
        orderChangeService.insertFlightOrderChange(orderChange);
        orderChange.getTicketNo().forEach(item -> {
            FlightOrderChangeTickets tickets = changeTicketsService.queryOrderChangeTickets(item);
            FlightOrderChangeTickets orderChangeTickets = new FlightOrderChangeTickets();
            orderChangeTickets.setChangeTicketId(snowflakeUtils.nextId());
            orderChangeTickets.setOrderId(Long.valueOf(orderChange.getOrderId()));
            orderChangeTickets.setChangeOrderId(orderChange.getChangeOrderId());
            orderChangeTickets.setFlight(tickets.getFlight());
            orderChangeTickets.setAirliner(tickets.getAirliner());
            orderChangeTickets.setCustomerId(orderInfo.getCustomerId());
            orderChangeTickets.setDepartureTime(tickets.getDepartureTime());
            orderChangeTickets.setIdTypeId(tickets.getIdTypeId());
            orderChangeTickets.setGuestName(tickets.getGuestName());
            orderChangeTickets.setTicketPrice(tickets.getTicketPrice());
            orderChangeTickets.setCabin(tickets.getCabin());
            orderChangeTickets.setArrivalTime(tickets.getArrivalTime());
            orderChangeTickets.setGuestType(tickets.getGuestType());
            orderChangeTickets.setGuestBirthday(tickets.getGuestBirthday());
            orderChangeTickets.setGuestIdno(tickets.getGuestIdno());
            orderChangeTickets.setOldTicketNo(tickets.getTicketNo());
            orderChangeTickets.setPlaneStyle(tickets.getPlaneStyle());
            orderChangeTickets.setDepTerm(tickets.getDepTerm());
            orderChangeTickets.setArrTerm(tickets.getArrTerm());
            orderChangeTickets.setPnr(tickets.getPnr());
            orderChangeTickets.setBigPnr(tickets.getBigPnr());
            orderChangeTickets.setDeparture(tickets.getDeparture());
            orderChangeTickets.setArrival(tickets.getArrival());
            orderChangeTickets.setOrgAirport(tickets.getOrgAirport());
            orderChangeTickets.setDstAirport(tickets.getDstAirport());
            orderChangeTickets.setGuestMobile(tickets.getGuestMobile());
            orderChangeTickets.setActionCode("XX");
            changeTicketsService.insertFlightOrderChangeTickets(orderChangeTickets);
        });

        int channelType = 0;
        if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            channelType = EnumHelper.RequestType.G5.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            channelType = EnumHelper.RequestType.DR.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            channelType = EnumHelper.RequestType.Qunar.getValue();
        }
        if (channelType == EnumHelper.RequestType.LinkStar.getValue()) { //领达
            FlightOrderChangeTickets tickets = changeTicketsService.queryOrderChangeTickets(orderChange.getTicketNo().get(0));
            TicketInfoResponse ticketInfo = linkStar.ticketInfo(tickets.getPnr());
            if (!ticketInfo.isSuccess()) {
                response.ErrorMsg = ticketInfo.getMsg();
                response.ErrorCode = ticketInfo.getCode();
                response.IsSuccess = false;
                return response;
            }
            //先判断这个订单出票渠道是b2b还是bsp,如果是bsp的则可以申请退票，其他转人工
            //获取出票渠道信息
            FlightChannelRule channelRule = channelRuleService.selectFlightChannelInfo(tickets.getAirliner());
            //获取出票渠道详细信息
            FlightInterface flightInterface = interfaceService.selectFlightInterfaceByAirCodeAndType(channelRule.getAirlinerId(), Long.valueOf(channelRule.getPeksourcetype()));
            if (flightInterface.getSourcetype() != Integer.parseInt(FlightOrderConstants.bsp.getValue())) {
                response.ErrorMsg = "此订单不支持自动退票，请转人工处理！";
                response.IsSuccess = false;
                return response;
            }
            MoCancelOrderResponse orderResponse = linkStar._changeCancelOrder(tickets.getPnr());
            boolean isSuccess = orderResponse.ListOrderItem.get(0).IsSuccess;
            if (!isSuccess) {
                response.IsSuccess = false;
                response.ErrorMsg = orderResponse.ListOrderItem.get(0).ErrorMsg;
                response.ErrorCode = orderResponse.ListOrderItem.get(0).ErrorCode;
                return response;
            }
            //执行退票
            response = linkStar._changeOrderRefundCRM(moRequest);

            FinanceOrderRefundment refundment = new FinanceOrderRefundment();
            refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.flight.getValue()));
            refundment.setCustomerId(orderInfo.getCustomerId());
            refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
            //TODO 测试阶段，手续费为0，后期完善手续费
            for (FlightOrderChangeTickets orderChangeTickets : ticketsList) {
                if (orderChangeTickets.getTicketNo().equals(moRequest.ticketNo)) {
                    if (response.IsSuccess) {
                        orderChangeTickets.setStatus(FlightOrderConstants.refundTicketStatus_success.toString());
                        changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    }
                    BigDecimal multiply = orderInfo.getPayAmount().multiply(new BigDecimal(orderInfoTickets.size()));
                    if (orderChangeTickets.getChangeFee() != null) {
                        BigDecimal add = multiply.add(orderChangeTickets.getChangeFee()).subtract(orderChange.getChangeFee());
                        refundment.setRefundmentAmount(add);
                    }
                }
            }
            //refundment.setRefundmentAmount(orderInfo.getPayAmount());
            refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
            refundment.setOrderId(String.valueOf(orderInfo.getOrderId()));
            refundment.setApplyTime(new Date());
            if (orderInfo.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
                refundment.setPaymentTypeId("2");
            } else if (orderInfo.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
                refundment.setPaymentTypeId("1");
            }
            refundment.setSerialnumber(orderInfo.getBillNo());
            remoteCustomerService.add(refundment);
        }
        if (response.IsSuccess) {
            orderChange.setChangeStatus(FlightOrderConstants.refundTicketStatus_success.getValue()); //退票状态
            orderChange.setRefundNumber(response.refundNumber);
            orderChangeService.updateFlightOrderChange(orderChange);
        }
        return response;
    }


    /**
     * 机票改签
     *
     * @param changeRequest
     * @return
     */
    @Override
    public MoOrderChangeResponse ticketChangeFlight(MoOrderChangeRequest changeRequest) {
        int channelType = changeRequest.channelType; //渠道类型
        MoOrderChangeResponse response = null;
        if (channelType == EnumHelper.RequestType.LinkStar.getValue()) {
            response = linkStar._OrderChange(changeRequest);
        } else if (channelType == EnumHelper.RequestType.DR.getValue()) {
            // todo 不支持改签
        } else if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
            response = qunar._OrderChange(changeRequest);
        } else if (channelType == EnumHelper.RequestType.G5.getValue()) {
            //todo 没有改签
        } else if (channelType == EnumHelper.RequestType.HangBanGuanJia.getValue()) {
            response = hangBanGuanJia.orderChange(changeRequest);
        }
        return response;
    }


    @Override
    public FlightPublishPriceResVo publishPrice(FlightPublishPriceReqVo vo) {
        return linkStar.publishPrice(vo);
    }

    //客票变更搜索(改签航班查询)
    @Override
    public List<FlightVo> changeSearchFlight(ChangeFlightRequest request) {
        MoFlightSearchResponse flight = linkStar.changeSearchFlight(request);
        String logo = filesService.airlineLogo();
        List<Airliner> airliners = airlinerMapper.selectAirlinerList(null);
        List<FlightVo> flightListVo = getFlightListVo(flight.ListGoFlightInfo, logo, EnumHelper.RequestType.LinkStar.getValue(), null, airliners);
        for (FlightVo flightVo : flightListVo) {
            List<CabinInfoVo> lstCabinY = new ArrayList<>();
            List<CabinInfoVo> lstCabinC = new ArrayList<>();
            List<CabinInfoVo> lstCabinF = new ArrayList<>();
            for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                if (StringHelper.isNullOrEmpty(cabinInfoVo.getBaseCabin())) {
                    continue;
                }
                if (cabinInfoVo.getBaseCabin().equals("Y") || cabinInfoVo.getBaseCabin().equals("ECONOMY")) {
                    lstCabinY.add(cabinInfoVo);
                }
                if (cabinInfoVo.getBaseCabin().equals("C") || cabinInfoVo.getBaseCabin().equals("J")) {
                    lstCabinC.add(cabinInfoVo);
                }
                if (cabinInfoVo.getBaseCabin().equals("F")) {
                    lstCabinF.add(cabinInfoVo);
                }
            }
            flightVo.getLstCabinGroup().add(lstCabinY);
            flightVo.getLstCabinGroup().add(lstCabinC);
            flightVo.getLstCabinGroup().add(lstCabinF);
        }
        return flightListVo;
    }

    //客票变更搜索（改签航班详情）
    @Override
    public FlightVo changeDetails(ChangeFlightRequest request) {
        List<FlightVo> flightVos = changeSearchFlight(request);
        for (FlightVo flightVo : flightVos) {
            if (flightVo.getFlightNo().equals(request.getNewFlightNo())) {
                return flightVo;
            }
        }
        return null;
    }

    //改签生成订单
    @Override
    public FlightOrderResponse changeCreateOrder(ChangeCreateOrder order) {
        FlightOrderResponse orderResponse = new FlightOrderResponse();
        MoCreateOrderRequest moRequest = new MoCreateOrderRequest();
        FlightOrderChange orderChange = new FlightOrderChange();
        FlightOrderChangeTickets orderChangeTickets = new FlightOrderChangeTickets();
        FlightOrderInfo flightOrderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(order.getOrderId()));
        List<FlightOrderInfoTickets> infoTickets = orderInfoTicketsService.selectOrderInfoTicketByOrderId(Long.valueOf(order.getOrderId()));
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        long nextId = snowflakeUtils.nextId();
        for (FlightOrderInfoTickets infoTicket : infoTickets) {
            if (order.getTicketNo().equals(infoTicket.getTicketNo())) {
                infoTicket.setStatus(FlightOrderConstants.rescheduled.getValue());
                orderInfoTicketsService.updateFlightOrderInfoTickets(infoTicket);
                MoSegment segment = new MoSegment();
                segment.Airline = infoTicket.getAirliner();
                segment.ArrDate = order.getArrTime();
                segment.Cabin = order.getCabin();
                segment.DepDate = order.getDepartureTime();
                segment.DstAirport = infoTicket.getDstAirport();
                segment.FlightNo = order.getFlightNo();
                segment.OilFee = order.getOilFee();
                segment.OrgAirport = infoTicket.getOrgAirport();
                segment.PlaneStyle = order.getPlaneStyle();
                segment.Tax = order.getTax();
                segment.orgTerminal = order.getOrgTerminal();
                segment.dstTerminal = order.getDstTerminal();
                moRequest.ListGoSegment.add(segment);

                MoPassenger passenger = new MoPassenger();
                passenger.AirportTax = order.getTax();
                passenger.Birthday = infoTicket.getGuestBirthday();
                passenger.FuelTax = order.getOilFee();
                passenger.IDNO = infoTicket.getGuestIdno();
                passenger.IDType = Math.toIntExact(infoTicket.getIdTypeId());
                passenger.PassengerMobile = infoTicket.getGuestMobile();
                passenger.PassengerName = infoTicket.getGuestName();
                if (infoTicket.getGuestType().equals("成人")) {
                    passenger.PassengerType = 1;
                } else if (infoTicket.getGuestType().equals("儿童")) {
                    passenger.PassengerType = 2;
                } else if (infoTicket.getGuestType().equals("婴儿")) {
                    passenger.PassengerType = 3;
                }
                if (infoTicket.getGuestSex().equals("F")) {
                    passenger.Sex = false;
                } else if (infoTicket.getGuestSex().equals("M")) {
                    passenger.Sex = true;
                }
                passenger.TicketAmount = order.getTicketAmount();
                moRequest.ListMoPassenger.add(passenger);
                moRequest.TripType = 1;
                moRequest.channelType = 14;

                //机场信息
                Airport depAirport = airportService.getAirPortNameByRirPortCode(infoTicket.getOrgAirport());

                Airport ArrAirport = airportService.getAirPortNameByRirPortCode(infoTicket.getDstAirport());

                if (flightOrderInfo.getChangeOrderId() != null) {
                    orderChangeTickets.setChangeTicketId(nextId);
                    orderChangeTickets.setOrderId(Long.valueOf(order.getOrderId()));
                    orderChangeTickets.setChangeOrderId(flightOrderInfo.getChangeOrderId());
                    orderChangeTickets.setFlight(order.getFlightNo());
                    orderChangeTickets.setAirliner(infoTickets.get(0).getAirliner());
                    orderChangeTickets.setCustomerId(flightOrderInfo.getCustomerId());
                    orderChangeTickets.setDepartureTime(order.getDepartureTime());
                    orderChangeTickets.setIdTypeId(infoTicket.getIdTypeId());
                    orderChangeTickets.setGuestName(infoTicket.getGuestName());
                    orderChangeTickets.setTicketPrice(order.getTicketAmount());
                    orderChangeTickets.setCabin(order.getCabin());
                    orderChangeTickets.setArrivalTime(order.getArrTime());
                    orderChangeTickets.setGuestType(infoTicket.getGuestType());
                    orderChangeTickets.setGuestBirthday(infoTicket.getGuestBirthday());
                    orderChangeTickets.setGuestIdno(infoTicket.getGuestIdno());
                    orderChangeTickets.setOldTicketNo(order.getTicketNo());
                    orderChangeTickets.setPlaneStyle(order.getPlaneStyle());
                    orderChangeTickets.setDepTerm(depAirport.getAirnamesort() + order.getOrgTerminal());
                    orderChangeTickets.setArrTerm(ArrAirport.getAirnamesort() + order.getDstTerminal());
                    orderChangeTickets.setDeparture(infoTicket.getDeparture());
                    orderChangeTickets.setArrival(infoTicket.getArrival());
                    orderChangeTickets.setOrgAirport(infoTicket.getOrgAirport());
                    orderChangeTickets.setDstAirport(infoTicket.getDstAirport());
                    orderChangeTickets.setGuestMobile(infoTicket.getGuestMobile());
                    orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.waitPay.getValue());
                    orderChangeTickets.setStatus(FlightOrderConstants.waitPay.getValue());
                    if (order.getSourceTypeId() != null && !order.getSourceTypeId().equals(""))
                        orderChangeTickets.setSourceTypeId(order.getSourceTypeId());
                    changeTicketsService.insertFlightOrderChangeTickets(orderChangeTickets);
                } else {
                    orderChange.setChangeOrderId(order.getOrderId() + "-G");
                    orderChange.setIsdealing("1");
                    orderChange.setOrderId(order.getOrderId());
                    orderChange.setOperationTime(new Date());
                    orderChange.setAddTime(new Date());
                    orderChange.setChangeType(FlightOrderChangeConstants.change.getValue());
                    orderChange.setCardnumber(flightOrderInfo.getCustomerCardId());
                    orderChange.setCardholder(flightOrderInfo.getCustomerName());
                    orderChangeService.insertFlightOrderChange(orderChange);
                    FlightOrderInfo info = new FlightOrderInfo();
                    info.setOrderId(Long.valueOf(order.getOrderId()));
                    info.setChangeOrderId(orderChange.getChangeOrderId());
                    orderInfoService.updateFlightOrderInfo(info);
                    orderChangeTickets.setChangeTicketId(nextId);
                    orderChangeTickets.setOrderId(Long.valueOf(order.getOrderId()));
                    orderChangeTickets.setChangeOrderId(orderChange.getChangeOrderId());
                    orderChangeTickets.setFlight(order.getFlightNo());
                    orderChangeTickets.setAirliner(infoTickets.get(0).getAirliner());
                    orderChangeTickets.setCustomerId(flightOrderInfo.getCustomerId());
                    orderChangeTickets.setDepartureTime(order.getDepartureTime());
                    orderChangeTickets.setIdTypeId(infoTicket.getIdTypeId());
                    orderChangeTickets.setGuestName(infoTicket.getGuestName());
                    orderChangeTickets.setTicketPrice(order.getTicketAmount());
                    orderChangeTickets.setCabin(order.getCabin());
                    orderChangeTickets.setArrivalTime(order.getArrTime());
                    orderChangeTickets.setGuestType(infoTicket.getGuestType());
                    orderChangeTickets.setGuestBirthday(infoTicket.getGuestBirthday());
                    orderChangeTickets.setGuestIdno(infoTicket.getGuestIdno());
                    orderChangeTickets.setOldTicketNo(order.getTicketNo());
                    orderChangeTickets.setPlaneStyle(order.getPlaneStyle());
                    orderChangeTickets.setDepTerm(depAirport.getAirnamesort() + order.getOrgTerminal());
                    orderChangeTickets.setArrTerm(ArrAirport.getAirnamesort() + order.getDstTerminal());
                    orderChangeTickets.setDeparture(infoTicket.getDeparture());
                    orderChangeTickets.setArrival(infoTicket.getArrival());
                    orderChangeTickets.setOrgAirport(infoTicket.getOrgAirport());
                    orderChangeTickets.setDstAirport(infoTicket.getDstAirport());
                    orderChangeTickets.setGuestMobile(infoTicket.getGuestMobile());
                    orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.waitPay.getValue());
                    orderChangeTickets.setStatus(FlightOrderConstants.waitPay.getValue());
                    if (order.getSourceTypeId() != null && !order.getSourceTypeId().equals(""))
                        orderChangeTickets.setSourceTypeId(order.getSourceTypeId());
                    changeTicketsService.insertFlightOrderChangeTickets(orderChangeTickets);
                }
                infoTicket.setStatus(FlightOrderConstants.rescheduled.getValue());
                orderInfoTicketsService.updateFlightOrderInfoTickets(infoTicket);
            }
        }
        List<FlightOrderInfoTickets> infoTicketsList = orderInfoTicketsService.selectOrderInfoTicketByOrderId(Long.valueOf(order.getOrderId()));
        boolean match = infoTicketsList.stream().allMatch(item -> item.getStatus() != null && item.getStatus().equals("rescheduled"));
        boolean allMatch = infoTicketsList.stream().allMatch(item -> item.getStatus() != null && item.getStatus().equals("changeTicketSuccess"));
        if (match) {
            flightOrderInfo.setStatus(FlightOrderConstants.rescheduled.getValue());
            orderInfoService.updateFlightOrderInfo(flightOrderInfo);
        }
        if (allMatch) {
            flightOrderInfo.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
            orderInfoService.updateFlightOrderInfo(flightOrderInfo);
        }
        moRequest.Contacts.ContactMobile = flightOrderInfo.getContactMobile();
        MoCreateOrderResponse response = linkStar._OrderCreate(moRequest);
        if (response.IsSuccess) {
            //查询运价
            CalculationResponse calculationResponse = linkStar.calculationFreight(response.MainOrderID);
            if (calculationResponse.isSuccess()) {
                //PNR结构化信息提取，获取下单后的航司大编
                MoQueryOrderRequest orderRequest = new MoQueryOrderRequest();
                orderRequest.OrderID = response.MainOrderID;
                MoQueryOrderResponse orderResponse1 = linkStar._QueryOrderInfo(orderRequest);
                String bigPnr = orderResponse1.bigPnr;

                //总金额 = 票价 + 基建+ 燃油
                BigDecimal totalPay = new BigDecimal(calculationResponse.getAmount()).add(new BigDecimal(calculationResponse.getFuelTax())).add(new BigDecimal(calculationResponse.getAirportTax()));
                orderChangeTickets.setChangeTicketId(nextId);
                orderChangeTickets.setPnr(response.MainOrderID);
                orderChangeTickets.setBigPnr(bigPnr);
                orderChangeTickets.setFullPrice(totalPay);
                orderChangeTickets.setActionCode(response.actionCode);
                orderChangeTickets.setPnrMark(response.ErrorMsg);
                changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                orderResponse.setHasSuccess(true);
                orderResponse.setOrderId(String.valueOf(nextId));
                orderResponse.setMsg(response.MainOrderID);
                orderResponse.setPayAmount(totalPay);
                orderResponse.setOldOrderId(order.getOrderId());
                orderResponse.setOldPnr(flightOrderInfo.getPnr());
                orderResponse.setOldTicketNo(order.getTicketNo());
            } else {
                orderChangeTickets.setPnrMark(calculationResponse.getMsg());
                changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                orderResponse.setHasSuccess(false);
                orderResponse.setMsg("预订失败");
            }
        } else {
            orderResponse.setHasSuccess(false);
            orderResponse.setMsg(response.ErrorMsg);
            orderChangeTickets.setPnrMark(response.ErrorMsg);
            changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
        }
        return orderResponse;
    }

    /**
     * 取消改签
     * @param flightCancelChange
     * @return
     */
    @Override
    public int cancelChange(FlightCancelChangeVO flightCancelChange) {
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(flightCancelChange.getOrderId()));
        if (flightOrderInfo == null)
            return 0;
        List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(Long.valueOf(flightCancelChange.getOrderId()));
        if (flightOrderInfoTickets == null && flightOrderInfoTickets.size() == 0)
            return 0;
        List<FlightOrderChangeTickets> flightOrderChangeTickets = changeTicketsService.queryChangeTicketsByOrderId(Long.valueOf(flightCancelChange.getOrderId()));
        if (flightOrderChangeTickets == null && flightOrderChangeTickets.size() == 0)
            return 0;
        flightOrderInfo.setStatus(FlightOrderConstants.noTravel.getValue());
        int orderInfo = flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
        if (orderInfo <= 0)
            return 0;
        for (FlightOrderInfoTickets flightOrderInfoTicket : flightOrderInfoTickets) {
            for (String ticketNo : flightCancelChange.getTicketNo()) {
                if (flightOrderInfoTicket.getTicketNo().equals(ticketNo)) {
                    flightOrderInfoTicket.setStatus(FlightOrderConstants.ticketing.getValue());
                    int orderInfoTickets = flightOrderInfoTicketsMapper.updateFlightOrderInfoTickets(flightOrderInfoTicket);
                    if (orderInfoTickets <= 0)
                        return 0;
                }
            }
        }
        for (FlightOrderChangeTickets flightOrderChangeTicket : flightOrderChangeTickets) {
            for (String ticketNo : flightCancelChange.getTicketNo()) {
                if (flightOrderChangeTicket.getOldTicketNo().equals(ticketNo)) {
                    if (flightOrderChangeTicket.getPnr() != null && !flightOrderChangeTicket.getPnr().equals("")) {
                        linkStar._changeCancelOrder(flightOrderChangeTicket.getPnr());
                    }

                    flightOrderChangeTicket.setStatus(FlightOrderConstants.cancelled.getValue());
                    flightOrderChangeTicket.setGuestPymtStsId(FlightOrderConstants.cancelled.getValue());
                    int orderChangeTickets = changeTicketsService.updateFlightOrderChangeTickets(flightOrderChangeTicket);
                    if (orderChangeTickets <= 0)
                        return 0;
                }
            }
        }
        return 1;
    }

    //计算改签费用（领达使用）
    @Override
    public ReIssuePriceResponse testAirReIssuePrice(AirReIssuePriceRequest request) {
        ReIssuePriceResponse response = linkStar.airReIssuePrice(request);
        return response;
    }

    @Override
    public CalculateRefundRes orderRefundConfirm(List<String> ticketNo, boolean voluntary) {
        return linkStar.autoCalculateRefundFee(ticketNo, voluntary);
    }

    /**
     * 机票查询常用旅客
     */
    @Override
    public FileCommonTravelersVo fileCommonTravelers(String token) throws Exception {
        String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
                "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        FileCommonTravelersVo fileCommonTravelersVo = new FileCommonTravelersVo();
        List<Letter> letterList = new ArrayList<>();

        R<Customer> loginCustomerByToken = remoteCustomerService.getLoginCustomerByToken(token);
        if (loginCustomerByToken.getData() == null) {
            throw new Exception("登录已过期，请重新登录");
        }
        Long customerId = loginCustomerByToken.getData().getCustomerId();
        String phone = loginCustomerByToken.getData().getContractPhoneOne();
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);

        List<com.ktgj.customer.api.domain.CommonTravelers> commonTravelersList = remoteCustomerService.fileCommonTravelers(map);

        for (String letter : letters) {
            Letter sort = new Letter();
            sort.setLetter(letter);
            List<FileCommonTravelers> fileCommonTravelersList = new ArrayList<>();

            if (commonTravelersList != null && commonTravelersList.size() > 0) {
                for (com.ktgj.customer.api.domain.CommonTravelers commonTravelers : commonTravelersList) {
                    if (commonTravelers.getIsDeletes().equals("false")) {
                        String pinYinHeadChar = getPinYinHeadChar(commonTravelers.getChineseName()).substring(0, 1);//获取首字母

                        if (pinYinHeadChar.equals(letter)) {
                            FileCommonTravelers fileCommonTravelers = new FileCommonTravelers();
                            fileCommonTravelers.setCommonTrvelersId(commonTravelers.getCommonTrvelersId().toString());
                            fileCommonTravelers.setChineseName(commonTravelers.getChineseName());
                            fileCommonTravelers.setEnglishSurname(commonTravelers.getEnglishSurname());
                            fileCommonTravelers.setEnglishName(commonTravelers.getEnglishName());
                            fileCommonTravelers.setDomesticPhone(commonTravelers.getDomesticPhone());
                            fileCommonTravelers.setTicketType(commonTravelers.getTicketType());
                            fileCommonTravelers.setGender(commonTravelers.getGender());
                            if (commonTravelers.getDateOfBirth() != null)
                                fileCommonTravelers.setBirthday(commonTravelers.getDateOfBirth());
                            if (phone.equals(commonTravelers.getDomesticPhone())) {
                                fileCommonTravelers.setMyself("true");
                            } else {
                                fileCommonTravelers.setMyself("false");
                            }

                            PassengerDocuments passengerDocuments = passengerDocuments(commonTravelers.getCommonTrvelersId());
                            FilePassengerDocuments filePassengerDocuments = new FilePassengerDocuments();
                            if (passengerDocuments != null) {
                                if (fileCommonTravelers.getBirthday() == null) {
                                    if (passengerDocuments.getCertificateType().equals(EmHelper.CertificateType.ID_CARD.getValue())) {
                                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                        String birthDay = extractYearMonthDayOfIdCard(passengerDocuments.getCertificateNumcer());
                                        if (birthDay != null && !birthDay.equals(""))
                                            fileCommonTravelers.setBirthday(dateFormat.parse(birthDay));
                                    }
                                }
                                filePassengerDocuments.setPassengerDocumentsId(passengerDocuments.getPassengerDocumentsId());
                                filePassengerDocuments.setCommontrvelersId(passengerDocuments.getCommontrvelersId().toString());
                                filePassengerDocuments.setCertificateType(passengerDocuments.getCertificateType());
                                filePassengerDocuments.setCertificateName(passengerDocuments.getCertificateName());
                                filePassengerDocuments.setCertificateNumcer(passengerDocuments.getCertificateNumcer());
                                filePassengerDocuments.setCertificateDate(passengerDocuments.getCertificateDate());

                                if (passengerDocuments.getCertificateDate() != null && !passengerDocuments.getCertificateDate().equals("")) {
                                    Date date = new Date();
                                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                    Date time = format.parse(passengerDocuments.getCertificateDate());
                                    if (date.compareTo(time) < 0) {
                                        filePassengerDocuments.setValidPeriod("true");
                                    } else {
                                        filePassengerDocuments.setValidPeriod("false");
                                    }
                                }

                            }
                            fileCommonTravelers.setDocuments(filePassengerDocuments);
                            fileCommonTravelersList.add(fileCommonTravelers);
                        }
                    }
                }
            }

            sort.setFileCommonTravelers(fileCommonTravelersList);

            if (sort.getFileCommonTravelers() != null && sort.getFileCommonTravelers().size() > 0) {
                letterList.add(sort);
            }
        }
        fileCommonTravelersVo.setLetterList(letterList);
        return fileCommonTravelersVo;
    }

    @Override
    public List<FileCommonTravelers> bankCommonTravelers(Map<String, Object> map) throws Exception {
        List<CommonTravelers> commonTravelersList = remoteCustomerService.fileCommonTravelers(map);

        List<FileCommonTravelers> fileCommonTravelersList = new ArrayList<>();
        if (commonTravelersList != null && commonTravelersList.size() > 0){
            for (CommonTravelers commonTravelers : commonTravelersList) {
                if (commonTravelers.getIsDeletes().equals("false")) {
                    FileCommonTravelers fileCommonTravelers = new FileCommonTravelers();
                    fileCommonTravelers.setCommonTrvelersId(commonTravelers.getCommonTrvelersId().toString());
                    fileCommonTravelers.setChineseName(commonTravelers.getChineseName());
                    fileCommonTravelers.setEnglishSurname(commonTravelers.getEnglishSurname());
                    fileCommonTravelers.setEnglishName(commonTravelers.getEnglishName());
                    fileCommonTravelers.setDomesticPhone(commonTravelers.getDomesticPhone());
                    fileCommonTravelers.setTicketType(commonTravelers.getTicketType());
                    fileCommonTravelers.setGender(commonTravelers.getGender());

                    R<PassengerDocuments> passengerDocumentsR = remoteCustomerService.backSelectPassengerDocumentsBack(commonTravelers.getCommonTrvelersId());
                    FilePassengerDocuments filePassengerDocuments = new FilePassengerDocuments();
                    if (passengerDocumentsR.getCode() == 200 && passengerDocumentsR.getData() != null) {
                        PassengerDocuments passengerDocuments = passengerDocumentsR.getData();
                        filePassengerDocuments.setPassengerDocumentsId(passengerDocuments.getPassengerDocumentsId());
                        filePassengerDocuments.setCommontrvelersId(passengerDocuments.getCommontrvelersId().toString());
                        filePassengerDocuments.setCertificateType(passengerDocuments.getCertificateType());
                        filePassengerDocuments.setCertificateName(passengerDocuments.getCertificateName());
                        filePassengerDocuments.setCertificateNumcer(passengerDocuments.getCertificateNumcer());
                        filePassengerDocuments.setCertificateDate(passengerDocuments.getCertificateDate());

                        Date date = new Date();
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        if (passengerDocuments.getCertificateDate() != null && !passengerDocuments.getCertificateDate().equals("")) {
                            Date time;
                            try {
                                time = format.parse(passengerDocuments.getCertificateDate());
                            } catch (Exception e){
                                throw new Exception("日期转换错误");
                            }

                            if (date.compareTo(time) < 0) {
                                filePassengerDocuments.setValidPeriod("true");
                            } else {
                                filePassengerDocuments.setValidPeriod("false");
                            }
                        }

                    }
                    fileCommonTravelers.setDocuments(filePassengerDocuments);
                    fileCommonTravelersList.add(fileCommonTravelers);
                }
            }
        }
        else {
            throw new Exception("未查到数据");
        }
        return fileCommonTravelersList;
    }

    /**
     * 机票银行卡支付
     * */
    @Override
    public String bankCardPayment(FlightPayVo flightPayVo, HttpServletRequest request) throws Exception {
        FlightOrderInfo info = flightOrderInfoMapper.journeyFlightOrderInfo(Long.valueOf(flightPayVo.jsjOrderId));

        if (flightPayVo.amount != null && flightPayVo.amount.compareTo(new BigDecimal(0)) > 0){
            flightPayVo.moneyAmout = String.valueOf(new BigDecimal(flightPayVo.moneyAmout).subtract(flightPayVo.amount));

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登录已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票银行卡支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(flightPayVo.payType);
            depositBusiness.setCustomerId(info.getCustomerId());
            depositBusiness.setDetailamount(flightPayVo.amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(flightPayVo.jsjOrderId));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "机票银行卡支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        if (new BigDecimal(flightPayVo.moneyAmout).compareTo(new BigDecimal(0)) == 0){
            MoOrderPayRequest moRequest = new MoOrderPayRequest();
            moRequest.OrderID = flightPayVo.jsjOrderId;
            moRequest.PayMode = "bankCardPay";
            MoOrderPayResponse payOrder = flightService.payOrder(moRequest);
            System.out.println("订单号：" + flightPayVo.jsjOrderId + "\n支付信息：" + payOrder.PayInfo.toString());

            Long billNo = System.currentTimeMillis() / 1000;

            if (payOrder.IsSuccess) {
                FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(flightPayVo.jsjOrderId));
                orderInfo.setOrderId(Long.valueOf(flightPayVo.jsjOrderId));
                orderInfo.setBillNo(billNo.toString());
                orderInfo.setPayTime(new Date());
                if (flightPayVo.Cvv2 != null && flightPayVo.Cvv2 != 0)
                    orderInfo.setPayType(BusinessTypeConstants.BankCredit.getValue());
                else
                    orderInfo.setPayType(BusinessTypeConstants.BankDebit.getValue());
                orderInfoService.updateFlightOrderInfo(orderInfo);
                FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
                infoTickets.setOrderId(orderInfo.getOrderId());
                List<FlightOrderInfoTickets> orderInfoTickets = orderInfoTicketsService.selectFlightOrderInfoTicketsList(infoTickets);
                Sms sms = new Sms();
                sms.setMobile(orderInfo.getContactMobile());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (orderInfo.getTripType().equals("ow") || orderInfo.getTripType().equals("ot")) {
                    String format = dateFormat.format(orderInfoTickets.get(0).getDepartureTime());
                    sms.setSmsContent("您购买的：" + format + "起飞，航班号：" + orderInfoTickets.get(0).getFlight() + " 已支付完成，请留意后续的出票信息");
                } else if (orderInfo.getTripType().equals("rt")) {
                    String formatGo = dateFormat.format(orderInfoTickets.get(0).getDepartureTime());
                    String formatBack = dateFormat.format(orderInfoTickets.get(1).getDepartureTime());
                    sms.setSmsContent("您购买的去程：" + formatGo + "起飞，航班号：" + orderInfoTickets.get(0).getFlight() + "，返程：" + formatBack + "起飞，航班号：" + orderInfoTickets.get(1).getFlight() + " 已支付完成，请留意后续的出票信息");
                }
                remoteSmsService.sendSmsMessage(sms);
            }

            if (flightPayVo.jsjOrderId != null && !flightPayVo.jsjOrderId.equals("") &&
                    flightPayVo.moneyAmout != null && !flightPayVo.moneyAmout.equals("")){

                int i = flightOrderCashInfoMapper.addFlightOrderCashInfo(flightPayVo.jsjOrderId,
                        billNo.toString(), flightPayVo.moneyAmout, EmHelper.cardType.Reserve_Money.getValue(), flightPayVo.type);

                if (i <= 0){
                    throw new Exception("支付信息存储异常，立刻联系后台人员");
                }
            }
            else {
                throw new Exception("未获取支付后的信息");
            }
            return "支付成功";
        }
        else {
            CustomerApi customer = new CustomerApi();
            customer.setCustCertificateNo(flightPayVo.custCertificateNo);
            customer.setContractPhoneOne(flightPayVo.contractPhoneOne);
            //银行卡信息
            BankCardApi card = new BankCardApi();
            card.setCardNumber(flightPayVo.cardNumber);
            card.setCardholder(flightPayVo.cardholder);

            Map<String, Object> map = new HashMap<>();
            map.put("cardNumber", flightPayVo.cardNumber);
            String backCard = remoteCustomerService.backCard(map);

            card.bankCode = backCard + "CREDIT";
            card.setCreditCardTime(flightPayVo.creditCardTime);
            card.setCvv2(flightPayVo.Cvv2);

            BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
            bankPayInfoApi.setJsjOrderId(flightPayVo.jsjOrderId);
            bankPayInfoApi.setMoneyAmout(flightPayVo.moneyAmout);
            bankPayInfoApi.setCustomer(customer);
            bankPayInfoApi.setCard(card);
            bankPayInfoApi.setPayType(flightPayVo.payType);

            YeeBaoResultApi yeeBaoResultApi;
            String payType;
            if (flightPayVo.type.equals("creditcard")){
                payType = BusinessTypeConstants.BankCredit.getValue();
                yeeBaoResultApi = remotePayService.CreditSale(bankPayInfoApi);
            }
            else if (flightPayVo.type.equals("debitcard")){
                payType = BusinessTypeConstants.BankDebit.getValue();
                yeeBaoResultApi = remotePayService.DebitSale(bankPayInfoApi);
            }
            else {
                throw new Exception("支付类型不明确");
            }

            System.out.println("订单号：" + flightPayVo.jsjOrderId);
            System.out.println("交易流水号：" + yeeBaoResultApi.getTrxId());

            if (yeeBaoResultApi.getCode().equals("1")){
                if (flightPayVo.jsjOrderId != null) {
                    MoOrderPayRequest moRequest = new MoOrderPayRequest();
                    moRequest.OrderID = flightPayVo.jsjOrderId;
                    moRequest.PayMode = "bankCardPay";
                    MoOrderPayResponse payOrder = flightService.payOrder(moRequest);
                    System.out.println("订单号：" + flightPayVo.jsjOrderId + "\n支付信息：" + payOrder.PayInfo.toString());

                    if (payOrder.IsSuccess) {
                        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(flightPayVo.jsjOrderId));
                        orderInfo.setOrderId(Long.valueOf(flightPayVo.jsjOrderId));
                        orderInfo.setBillNo(yeeBaoResultApi.getTrxId());
                        orderInfo.setPayTime(new Date());
                        if (flightPayVo.Cvv2 != null && flightPayVo.Cvv2 != 0)
                            orderInfo.setPayType(BusinessTypeConstants.BankCredit.getValue());
                        else
                            orderInfo.setPayType(BusinessTypeConstants.BankDebit.getValue());
                        orderInfoService.updateFlightOrderInfo(orderInfo);
                        FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
                        infoTickets.setOrderId(orderInfo.getOrderId());
                        List<FlightOrderInfoTickets> orderInfoTickets = orderInfoTicketsService.selectFlightOrderInfoTicketsList(infoTickets);
                        Sms sms = new Sms();
                        sms.setMobile(orderInfo.getContactMobile());
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if (orderInfo.getTripType().equals("ow") || orderInfo.getTripType().equals("ot")) {
                            String format = dateFormat.format(orderInfoTickets.get(0).getDepartureTime());
                            sms.setSmsContent("您购买的：" + format + "起飞，航班号：" + orderInfoTickets.get(0).getFlight() + " 已支付完成，请留意后续的出票信息");
                        } else if (orderInfo.getTripType().equals("rt")) {
                            String formatGo = dateFormat.format(orderInfoTickets.get(0).getDepartureTime());
                            String formatBack = dateFormat.format(orderInfoTickets.get(1).getDepartureTime());
                            sms.setSmsContent("您购买的去程：" + formatGo + "起飞，航班号：" + orderInfoTickets.get(0).getFlight() + "，返程：" + formatBack + "起飞，航班号：" + orderInfoTickets.get(1).getFlight() + " 已支付完成，请留意后续的出票信息");
                        }
                        remoteSmsService.sendSmsMessage(sms);
                    }

                    if (flightPayVo.jsjOrderId != null && !flightPayVo.jsjOrderId.equals("") &&
                            yeeBaoResultApi.getTrxId() != null && !yeeBaoResultApi.getTrxId().equals("") &&
                            flightPayVo.moneyAmout != null && !flightPayVo.moneyAmout.equals("")){

                        int i = flightOrderCashInfoMapper.addFlightOrderCashInfo(flightPayVo.jsjOrderId,
                                yeeBaoResultApi.getTrxId(), flightPayVo.moneyAmout, payType, flightPayVo.type);

                        if (i <= 0){
                            throw new Exception("支付信息存储异常，立刻联系后台人员");
                        }
                    }
                    else {
                        throw new Exception("未获取支付后的信息");
                    }
                }
                return "支付成功";
            }
            else {
                Date date = new Date();
                FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
                FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(flightPayVo.jsjOrderId));
                financeConsignPymtRecord.setOrderId(flightOrderInfo.getOrderId());
                financeConsignPymtRecord.setEmployeeId(10l);
                financeConsignPymtRecord.setPaymentTime(date);
                financeConsignPymtRecord.setPayStart("false");
                financeConsignPymtRecord.setPaymentAmount(new BigDecimal(flightPayVo.moneyAmout));
                financeConsignPymtRecord.setOperationTime(date);
                financeConsignPymtRecord.setPymtType(flightPayVo.type);
                financeConsignPymtRecord.setOrderAmount(new BigDecimal(flightPayVo.moneyAmout));
                financeConsignPymtRecord.setCreateTime(date);
                financeConsignPymtRecord.setRemark(yeeBaoResultApi.getErrorMsg());
                financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
                return yeeBaoResultApi.getErrorMsg();
            }
        }
    }

    //改签银行卡支付
    @Override
    public String changeBankCardPay(FlightPayVo flightPayVo, HttpServletRequest request) throws Exception {
        FlightOrderChangeTickets orderChangeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(flightPayVo.jsjOrderId));
        List<FlightOrderInfoTickets> infoTickets = orderInfoTicketsService.selectOrderInfoTicketByOrderId(orderChangeTickets.getOrderId());
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(infoTickets.get(0).getOrderId());

        if (flightPayVo.amount != null && flightPayVo.amount.compareTo(new BigDecimal(0)) > 0){
            flightOrderInfo.setPayAmount(flightOrderInfo.getPayAmount().subtract(flightPayVo.amount));
            if (flightOrderInfo.getDepositAmount() != null){
                flightOrderInfo.setDepositAmount(flightOrderInfo.getDepositAmount().add(flightPayVo.amount));
            }
            else {
                flightOrderInfo.setDepositAmount(flightPayVo.amount);
            }
            int i = flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登陆已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票改签银行卡支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(flightPayVo.payType);
            depositBusiness.setCustomerId(flightOrderInfo.getCustomerId());
            depositBusiness.setDetailamount(flightPayVo.amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(flightOrderInfo.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "机票改签银行卡支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        MoOrderChangeRequest changeRequest = new MoOrderChangeRequest();
        ChangeSegementInfo segementInfo = new ChangeSegementInfo();
        segementInfo.TakeoffDate = orderChangeTickets.getDepartureTime();
        segementInfo.ArrivalTime = orderChangeTickets.getArrivalTime();
        segementInfo.DestinFlight = orderChangeTickets.getFlight().substring(2);
        segementInfo.NewDPort = infoTickets.get(0).getOrgAirport();
        segementInfo.NewAPort = infoTickets.get(0).getDstAirport();
        segementInfo.airline = orderChangeTickets.getAirliner();
        segementInfo.NewClass = orderChangeTickets.getCabin();
        changeRequest.ListChangeSegementInfo.add(segementInfo);
        changeRequest.newOrderId = flightPayVo.jsjOrderId;
        changeRequest.pnr = orderChangeTickets.getPnr();
        changeRequest.ticketNo = orderChangeTickets.getOldTicketNo();
        changeRequest.TicketFee = orderChangeTickets.getTicketPrice();
        changeRequest.PayAmount = new BigDecimal(flightPayVo.moneyAmout);
        changeRequest.channelType = 14;
        if (new BigDecimal(flightPayVo.moneyAmout).compareTo(new BigDecimal(0)) == 0) {
            MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
            orderChangeTickets.setChangeFee(new BigDecimal(flightPayVo.moneyAmout));
            orderChangeTickets.setStatus(FlightOrderConstants.payd.getValue());
            orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.payd.getValue());
            changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
            if (response.IsSuccess) {
                Sms sms = new Sms();
                sms.setMobile(flightOrderInfo.getContactMobile());
                sms.setSmsContent("乘客：" + orderChangeTickets.getGuestName() + "改签成功。原航班：" + infoTickets.get(0).getFlight() + "，现航班：" + orderChangeTickets.getFlight());
                remoteSmsService.sendSmsMessage(sms);
                FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                orderInfoTickets.setOrderId(orderChangeTickets.getOrderId());
                orderInfoTickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                orderInfoTickets.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
                orderInfoTicketsService.updateFlightOrderInfoTicket(orderInfoTickets);
                orderChangeTickets.setStatus(FlightOrderConstants.noTravel.getValue());
                changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                return "改签申请成功";
            } else {
                FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                orderInfoTickets.setOrderId(orderChangeTickets.getOrderId());
                orderInfoTickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                orderInfoTickets.setStatus(FlightOrderConstants.changeTicketFail.getValue());
                orderInfoTicketsService.updateFlightOrderInfoTicket(orderInfoTickets);
                orderChangeTickets.setStatus(FlightOrderConstants.ticketingFail.getValue());
                changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                return "改签申请失败";
            }
        } else {
            if (new BigDecimal(0.1).compareTo(new BigDecimal(0)) == 0){
                if (flightPayVo.jsjOrderId != null) {
                    if (flightPayVo.Cvv2 != null && flightPayVo.Cvv2 != 0)
                        orderChangeTickets.setPayType(BusinessTypeConstants.BankCredit.getValue());
                    else
                        orderChangeTickets.setPayType(BusinessTypeConstants.BankDebit.getValue());
                    orderChangeTickets.setChangeFee(new BigDecimal(flightPayVo.moneyAmout));
                    orderChangeTickets.setSourceTypeId(flightPayVo.payType);
                    Long billNo = System.currentTimeMillis() / 1000;
                    orderChangeTickets.setBillNo(billNo.toString());
                    orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.payd.toString()); //已支付
                    orderChangeTickets.setStatus(FlightOrderConstants.noTravel.getValue());
                    changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
                    orderChangeTickets.setStatus(FlightOrderConstants.payd.getValue());
                    orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.payd.getValue());
                    changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    if (response.IsSuccess) {
                        Sms sms = new Sms();
                        sms.setMobile(flightOrderInfo.getContactMobile());
                        sms.setSmsContent("乘客：" + orderChangeTickets.getGuestName() + "改签支付成功。原航班：" + infoTickets.get(0).getFlight() + "，现航班：" + orderChangeTickets.getFlight() + "。请留意后续出票信息");
                        remoteSmsService.sendSmsMessage(sms);
                        FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                        orderInfoTickets.setOrderId(orderChangeTickets.getOrderId());
                        orderInfoTickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                        orderInfoTickets.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
                        orderInfoTicketsService.updateFlightOrderInfoTicket(orderInfoTickets);
                        orderChangeTickets.setStatus(FlightOrderConstants.noTravel.getValue());
                        changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    } else {
                        FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                        orderInfoTickets.setOrderId(orderChangeTickets.getOrderId());
                        orderInfoTickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                        orderInfoTickets.setStatus(FlightOrderConstants.changeTicketFail.getValue());
                        orderInfoTicketsService.updateFlightOrderInfoTicket(orderInfoTickets);
                        orderChangeTickets.setStatus(FlightOrderConstants.ticketingFail.getValue());
                        changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    }
                }
                return "支付成功";
            }

            CustomerApi customer = new CustomerApi();
            customer.setCustCertificateNo(flightPayVo.custCertificateNo);
            customer.setContractPhoneOne(flightPayVo.contractPhoneOne);
            //银行卡信息
            BankCardApi card = new BankCardApi();
            card.setCardNumber(flightPayVo.cardNumber);
            card.setCardholder(flightPayVo.cardholder);

            Map<String, Object> map = new HashMap<>();
            map.put("cardNumber", flightPayVo.cardNumber);
            String backCard = remoteCustomerService.backCard(map);

            card.bankCode = backCard + "CREDIT";
            card.setCreditCardTime(flightPayVo.creditCardTime);
            card.setCvv2(flightPayVo.Cvv2);

            BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
            bankPayInfoApi.setJsjOrderId(flightPayVo.jsjOrderId);
            bankPayInfoApi.setMoneyAmout("0.1");
            bankPayInfoApi.setCustomer(customer);
            bankPayInfoApi.setCard(card);
            bankPayInfoApi.setPayType(flightPayVo.payType);

            YeeBaoResultApi yeeBaoResultApi;
            if (flightPayVo.type.equals("creditcard")){
                yeeBaoResultApi = remotePayService.CreditSale(bankPayInfoApi);
            }
            else if (flightPayVo.type.equals("debitcard")){
                yeeBaoResultApi = remotePayService.DebitSale(bankPayInfoApi);
            }
            else {
                throw new Exception("支付类型不明确");
            }
            System.out.println("改签订单号：" + flightPayVo.jsjOrderId);
            System.out.println("改签交易流水号：" + yeeBaoResultApi.getTrxId());

            if (yeeBaoResultApi.getCode().equals("1")){
                if (flightPayVo.jsjOrderId != null) {
                    if (flightPayVo.Cvv2 != null && flightPayVo.Cvv2 != 0)
                        orderChangeTickets.setPayType(BusinessTypeConstants.BankCredit.getValue());
                    else
                        orderChangeTickets.setPayType(BusinessTypeConstants.BankDebit.getValue());
                    orderChangeTickets.setChangeFee(new BigDecimal(flightPayVo.moneyAmout));
                    orderChangeTickets.setSourceTypeId(flightPayVo.payType);
                    orderChangeTickets.setBillNo(yeeBaoResultApi.getTrxId());
                    orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.payd.toString()); //已支付
                    orderChangeTickets.setStatus(FlightOrderConstants.noTravel.getValue());
                    changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
                    orderChangeTickets.setStatus(FlightOrderConstants.payd.getValue());
                    orderChangeTickets.setGuestPymtStsId(FlightOrderConstants.payd.getValue());
                    changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    if (response.IsSuccess) {
                        Sms sms = new Sms();
                        sms.setMobile(flightOrderInfo.getContactMobile());
                        sms.setSmsContent("乘客：" + orderChangeTickets.getGuestName() + "改签支付成功。原航班：" + infoTickets.get(0).getFlight() + "，现航班：" + orderChangeTickets.getFlight() + "。请留意后续出票信息");
                        remoteSmsService.sendSmsMessage(sms);
                        FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                        orderInfoTickets.setOrderId(orderChangeTickets.getOrderId());
                        orderInfoTickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                        orderInfoTickets.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
                        orderInfoTicketsService.updateFlightOrderInfoTicket(orderInfoTickets);
                        orderChangeTickets.setStatus(FlightOrderConstants.noTravel.getValue());
                        changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    } else {
                        FlightOrderInfoTickets orderInfoTickets = new FlightOrderInfoTickets();
                        orderInfoTickets.setOrderId(orderChangeTickets.getOrderId());
                        orderInfoTickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                        orderInfoTickets.setStatus(FlightOrderConstants.changeTicketFail.getValue());
                        orderInfoTicketsService.updateFlightOrderInfoTicket(orderInfoTickets);
                        orderChangeTickets.setStatus(FlightOrderConstants.ticketingFail.getValue());
                        changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                    }
                }
                return "支付成功";
            }
            else {
                Date date = new Date();
                FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
                Long info = flightOrderInfoMapper.selectFlightOrderInfoByOrdernum(flightPayVo.jsjOrderId);
                financeConsignPymtRecord.setOrderId(info);
                financeConsignPymtRecord.setEmployeeId(10l);
                financeConsignPymtRecord.setPaymentTime(date);
                financeConsignPymtRecord.setPaymentAmount(new BigDecimal(flightPayVo.moneyAmout));
                financeConsignPymtRecord.setOperationTime(date);
                financeConsignPymtRecord.setPymtType(flightPayVo.type);
                financeConsignPymtRecord.setOrderAmount(new BigDecimal(flightPayVo.moneyAmout));
                financeConsignPymtRecord.setCreateTime(date);
                financeConsignPymtRecord.setRemark(yeeBaoResultApi.getErrorMsg());
                financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
                return yeeBaoResultApi.getErrorMsg();
            }
        }
    }

    @Override
    public boolean clearFlightCache(String depDate, String dstAirport, String orgAirport, String backDepDate) {
        //缓存key
        String redisKey = null;
        if (backDepDate != null && backDepDate.equals(""))
            redisKey = depDate + dstAirport + orgAirport;
        else
            redisKey = depDate + dstAirport + orgAirport + backDepDate;
        //先判断缓存中是否存在此次查询的结果
        Object redisData = redisService.getCacheObject(FLIGHT + redisKey);
        if (redisData!=null) {
            redisService.deleteObject(FLIGHT + redisKey);
            return true;
        }
        return false;
    }

    /**
     * 获取乘客证件信息
     */
    public PassengerDocuments passengerDocuments(Long commontrvelersId) {
        Map<String, Object> map = new HashMap<>();
        map.put("commontrvelersId", commontrvelersId);
        List<PassengerDocuments> documentsList = remoteCustomerService.selectDocumentsByCommontrvelersId(map);

        if (documentsList != null && documentsList.size() > 0) {
            int count = 0;
            int num = 0;
            PassengerDocuments passengerDocuments = null;
            for (int i = 0; i < documentsList.size(); i++) {
                if (documentsList.get(i).getIsDelete().equals("false")) {
                    if (documentsList.get(i).getCertificateType().equals(EmHelper.CertificateType.ID_CARD.getValue()) && count == 0) {//获取乘客身份证
                        passengerDocuments = documentsList.get(i);
                        break;
                    } else if (documentsList.get(i).getCertificateType().equals(EmHelper.CertificateType.PASSPORT.getValue()) && count == 1) {//获取乘客护照
                        passengerDocuments = documentsList.get(i);
                        break;
                    } else if (count == 2) {
                        passengerDocuments = documentsList.get(i);
                        break;
                    }

                    if (i == documentsList.size() - 1 && passengerDocuments != null) {
                        if (num == 0) {
                            count = 1;
                            i = 0;
                            num = 1;
                        } else {
                            count = 2;
                            i = 0;
                        }
                    }
                } else {
                    continue;
                }
            }
            return passengerDocuments;
        } else {
            return null;
        }
    }

    /**
     * 获取当前时间的后7个月时间并校验任意时间是否在该时间段内
     */
    public boolean dayTime(String eTime) {
        GregorianCalendar now = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        now.add(GregorianCalendar.MONTH, 7);
        String l = sdf.format(now.getTime());
        if (eTime.compareTo(l) <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取中文首字母
     */
    public static String getPinYinHeadChar(String str) {
        StringBuilder convert = new StringBuilder();
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        String toUpperCase = convert.toString().toUpperCase();
        return toUpperCase;
    }


    private List<FlightVo> getFlightListVo(List<MoFlightInfo> info, String logo, int channelType, List<FlightRevisecabinprice> revisecabinprices, List<Airliner> airliners) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<FlightVo> list = new ArrayList<>();
        //从数据库里把所有的退改签规则拿到
        List<FlightCabinrule> flightCabinrules = flightCabinruleService.selectFlightCabinRule();
        //从数据库里把所有的仓位等级拿到
        List<CabinLevel> cabinLevels = flightCabinruleService.queryCabinLevelList();
        List<PlaneType> planeTypes = planeTypeService.selectPlaneTypeList(null);
        List<Airport> airports = airportService.selectAirportList(null);
        info.forEach(item -> {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR,2);
            Date time = calendar.getTime();
            boolean before = item.DepDate.before(time);
            //航班信息
            FlightVo vo = new FlightVo();
            BeanUtils.copyProperties(item, vo);
            vo.setStopDate(item.stopDate);
            vo.setStopEndDate(item.stopEndDate);
            vo.setChannelType(channelType);
            if (before)
                vo.setNearFlight(true);
            else
                vo.setNearFlight(false);
            if (channelType == 14) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(item.Airline);
                buffer.append(item.FlightNo);
                vo.setFlightNo(buffer.toString());
            }
            if (item.IsCodeShare != null && item.IsCodeShare) {
                vo.setCodeShare(true);
                vo.setCarrier(item.Carrier);
            } else
                vo.setCodeShare(false);
            vo.setArrDate(format.format(item.ArrDate));
            vo.setDepDate(format.format(item.DepDate));
            vo.setFlightTimes(item.flightTimes);
            vo.setAirlineCode(item.Airline);
            if (item.Airline != null && !item.Airline.equals("")) {
                for (Airliner airliner : airliners) {
                    if (airliner.getAirlinerId().equals(item.Airline)) {
                        vo.setAirline(airliner.getAirlinerShorter());
                        break;
                    }
                }
            }
            if (item.Carrier != null && !item.Carrier.equals("")) {
                for (Airliner airliner : airliners) {
                    if (airliner.getAirlinerId().equals(item.Carrier.substring(0, 2))) {
                        vo.setCarrier(airliner.getAirlinerShorter() + " " + item.Carrier);
                        break;
                    }
                }
            }
            vo.setDepad(item.depad);
            vo.setArrad(item.arrad);
            vo.setAirlineGif(logo + item.Airline + ".gif");

            PlaneType planeType = planeTypes.stream().filter(type -> type.getPlaneTypeId().equals(item.PlaneStyle)).findFirst().orElse(null);
            if (planeType != null) {
                vo.setPlaneStyle(planeType.getAirlineType());
                vo.setPlaneTypeDesc(planeType.getPlaneTypeDesc());
                vo.setWidthType(planeType.getWidthType());
            } else {
                vo.setPlaneStyle(null);
                vo.setPlaneTypeDesc(item.PlaneStyle);
                vo.setWidthType(null);
            }
            vo.setStopCount(item.StopCount);
            if (item.StopCount > 0) {
                Airport port = airports.stream().filter(airport -> airport.getAirportId().equals(item.stopPlace)).findFirst().orElse(null);
                if (port != null)
                    vo.setStopPlace(port.getAirportCityName());
                vo.setStopTime(item.stopTime);
            } else {
                Airport port = airports.stream().filter(airport -> airport.getAirportId().equals(item.DstAirport)).findFirst().orElse(null);
                if (port != null)
                    vo.setStopPlace(port.getAirportCityName());
                vo.setStopTime(item.stopTime);
            }
            if (item.StopCount > 0 && channelType == 19) {
                for (FlightStopEntity flightStopEntity : item.ListFlightStop) {
                    vo.setStopPlace(flightStopEntity.StopCityCode);
                    vo.setStopTime(String.valueOf(flightStopEntity.Duration));
                }
            }

            List<CabinInfoVo> cabinInfoVos = new ArrayList<>();
            item.ListCabinInfo.forEach(cabinInfo -> {
                CabinInfoVo infoVo = new CabinInfoVo();
                infoVo.setCabin(cabinInfo.Cabin);
                infoVo.setTicketPrice(cabinInfo.CallCenterAmountInfo.OrgTicketAmount);
                infoVo.setChdTicketPrice(cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount);
                infoVo.setInfTicketPrice(cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount);
                infoVo.setCabinMark(cabinInfo.CabinMark);
                infoVo.setBaseCabinName(cabinInfo.BaseCabinName);
                infoVo.setBaseCabin(cabinInfo.BaseCabin);
                infoVo.setCabinLeftDesc(cabinInfo.CabinLeftDesc);
                if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
                    infoVo.setDisCountRate(cabinInfo.CallCenterAmountInfo.DisCountRate);
                } else {
                    if (cabinInfo.CallCenterAmountInfo.OrgTicketAmount != null && cabinInfo.CallCenterAmountInfo.TicketAmount != null && cabinInfo.CallCenterAmountInfo.TicketAmount.intValue() > 0) {
                        BigDecimal multiply = null;
                        BigDecimal divide = cabinInfo.CallCenterAmountInfo.OrgTicketAmount.divide(cabinInfo.CallCenterAmountInfo.TicketAmount, 2, BigDecimal.ROUND_HALF_UP);
                        if (divide.compareTo(new BigDecimal(1)) > 0)
                            multiply = new BigDecimal(1).multiply(new BigDecimal(100));
                        else
                            multiply = divide.multiply(new BigDecimal(100));
                        infoVo.setDisCountRate(multiply);
                    }
                }

                if (channelType == EnumHelper.RequestType.LinkStar.getValue()) {
                    for (FlightCabinrule flightCabinrule : flightCabinrules) {
                        if (flightCabinrule.getAirline().equals(item.Airline) && flightCabinrule.getCabin().indexOf(cabinInfo.Cabin.substring(0, 1)) >= 0) {
                            for (CabinLevel cabinLevel : cabinLevels) {
                                if (flightCabinrule.getCabinlevel() == cabinLevel.getCabinLevelId()) {
                                    infoVo.setBaseCabinName(cabinLevel.getCabinLevelName());
                                    break;
                                }
                            }
                            break;
                        }
                    }
                } else {
                    infoVo.setBaseCabinName(cabinInfo.BaseCabinName);
                }

                if (cabinInfo.CabinRule != null) {
                    if (cabinInfo.CabinRule.refundChangeRules.size() > 0)
                        infoVo.getRefundChangeRules().addAll(cabinInfo.CabinRule.refundChangeRules);
                    if (cabinInfo.CabinRule.changeRules.size() > 0)
                        infoVo.getChangeRules().addAll(cabinInfo.CabinRule.changeRules);
                }
                if (cabinInfo.ChdCabinRule != null) {
                    infoVo.setChdBaggage(cabinInfo.ChdCabinRule.Baggage);
                    if (cabinInfo.ChdCabinRule.refundChangeRules.size() > 0)
                        infoVo.getChdRefundChangeRules().addAll(cabinInfo.ChdCabinRule.refundChangeRules);
                    if (cabinInfo.ChdCabinRule.changeRules.size() > 0)
                        infoVo.getChdChangeRules().addAll(cabinInfo.ChdCabinRule.changeRules);
                }
                if (cabinInfo.IftCabinRule != null) {
                    if (cabinInfo.IftCabinRule.refundChangeRules.size() > 0)
                        infoVo.getInfRefundChangeRules().addAll(cabinInfo.IftCabinRule.refundChangeRules);
                    if (cabinInfo.IftCabinRule.changeRules.size() > 0)
                        infoVo.getInfChangeRules().addAll(cabinInfo.IftCabinRule.changeRules);
                }
                infoVo.setPrice(cabinInfo.CallCenterAmountInfo.OrgTicketAmount);
                infoVo.setChdPrice(cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount);
                infoVo.setInfPrice(cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount);
                vo.setMeal(cabinInfo.Meal);

                if (revisecabinprices != null && revisecabinprices.size() > 0) {
                    for (FlightRevisecabinprice revisecabinprice : revisecabinprices) {
                        if (item.Airline.equals(revisecabinprice.getAirlinerId())) {
                            vo.setReturnMoney(String.valueOf(revisecabinprice.getReturnMoney()));
                            vo.setSaleSexPlain(revisecabinprice.getSalesexplain());
                            String cabin = revisecabinprice.getCabin();
                            String[] splCabin = cabin.split(",");
                            for (String spl : splCabin) {
                                if (cabinInfo.Cabin.substring(0, 1).equals(spl)) {
                                    CabinInfoVo tmpInfoVo = new CabinInfoVo();
                                    if (cabinInfo.CabinRule.Baggage != null) {
                                        infoVo.setBaggage(cabinInfo.CabinRule.Baggage);
                                    } else {
                                        infoVo.setBaggage(revisecabinprice.getBaggage());
                                    }
                                    BeanUtils.copyProperties(infoVo, tmpInfoVo);
                                    if (infoVo.getRefundChangeRules().size() > 0)
                                        tmpInfoVo.getRefundChangeRules().addAll(infoVo.getRefundChangeRules());
                                    if (infoVo.getChangeRules().size() > 0)
                                        tmpInfoVo.getChangeRules().addAll(infoVo.getChangeRules());
                                    if (infoVo.getChdRefundChangeRules().size() > 0)
                                        tmpInfoVo.getChdRefundChangeRules().addAll(infoVo.getChdRefundChangeRules());
                                    if (infoVo.getChdChangeRules().size() > 0)
                                        tmpInfoVo.getChdChangeRules().addAll(infoVo.getChdChangeRules());
                                    if (infoVo.getInfRefundChangeRules().size() > 0)
                                        tmpInfoVo.getInfRefundChangeRules().addAll(infoVo.getInfRefundChangeRules());
                                    if (infoVo.getInfChangeRules().size() > 0)
                                        tmpInfoVo.getInfChangeRules().addAll(infoVo.getInfChangeRules());
                                    if (revisecabinprice.getAdjusttype() == 1) {
                                        if (revisecabinprice.getAdjustmoney().compareTo(new BigDecimal(0)) != 0) {
                                            BigDecimal divide = revisecabinprice.getAdjustmoney().divide(new BigDecimal(100));
                                            BigDecimal multiply = cabinInfo.CallCenterAmountInfo.OrgTicketAmount.multiply(divide);
                                            tmpInfoVo.setPrice(cabinInfo.CallCenterAmountInfo.OrgTicketAmount.add(multiply));
                                            if (cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount != null) {
                                                BigDecimal chdMultiply = cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount.multiply(divide);
                                                tmpInfoVo.setChdPrice(cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount.add(chdMultiply));
                                            }
                                            if (cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount != null) {
                                                BigDecimal iftMultiply = cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount.multiply(divide);
                                                tmpInfoVo.setInfPrice(cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount.add(iftMultiply));
                                            }
                                        }
                                    } else if (revisecabinprice.getAdjusttype() == 2) {
                                        tmpInfoVo.setPrice(cabinInfo.CallCenterAmountInfo.OrgTicketAmount.add(revisecabinprice.getAdjustmoney()));
                                        if (cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount != null)
                                            tmpInfoVo.setChdPrice(cabinInfo.CallCenterAmountInfo.OrgChdTicketAmount.add(revisecabinprice.getAdjustmoney()));
                                        if (cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount != null)
                                            tmpInfoVo.setInfPrice(cabinInfo.CallCenterAmountInfo.OrgIftTicketAmount.add(revisecabinprice.getAdjustmoney()));
                                    }
                                    if (channelType == EnumHelper.RequestType.Qunar.getValue()) {
                                        tmpInfoVo.setDisCountRate(cabinInfo.CallCenterAmountInfo.DisCountRate);
                                    } else {
                                        if (tmpInfoVo.getPrice() != null && cabinInfo.CallCenterAmountInfo.TicketAmount != null && cabinInfo.CallCenterAmountInfo.TicketAmount.intValue() > 0) {
                                            BigDecimal multiply = null;
                                            BigDecimal divide = tmpInfoVo.getPrice().divide(cabinInfo.CallCenterAmountInfo.TicketAmount, 2, BigDecimal.ROUND_HALF_UP);
                                            if (divide.compareTo(new BigDecimal(1)) > 0)
                                                multiply = new BigDecimal(1).multiply(new BigDecimal(100));
                                            else
                                                multiply = divide.multiply(new BigDecimal(100));
                                            tmpInfoVo.setDisCountRate(multiply);
                                        }
                                    }
                                    tmpInfoVo.setReturnMoney(String.valueOf(revisecabinprice.getReturnMoney()));
                                    tmpInfoVo.setCredentials(revisecabinprice.getCredentials());
                                    cabinInfoVos.add(tmpInfoVo);
                                } else
                                    infoVo.setCredentials("行程单");
                            }
                        } else
                            infoVo.setCredentials("行程单");
                    }
                } else
                    infoVo.setCredentials("行程单");
                cabinInfoVos.add(infoVo);
            });
            vo.getListCabinInfo().addAll(cabinInfoVos);
            list.add(vo);
        });
        return list;
    }

    /**
     * 保存订单信息
     */
    private FlightOrderResponse saveOrder(MoCreateOrderRequest moRequest, String token, String changType) {
        FlightOrderResponse response = new FlightOrderResponse();
        try {
            //获取会员信息
            R<Customer> customerInfo = customerService.getLoginCustomerByToken(token);
            Customer data = customerInfo.getData();
            if (data == null) {
                response.setMsg("会员信息获取失败！");
                response.setHasSuccess(false);
                return response;
            }
            //获取会员卡信息
            List<CustomerCard> customerCards = customerService.queryCardIdByCustomerId(data.getCustomerId());

            for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
                if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                    Map<String, Object> map = new HashMap<>();
                    map.put("cardId", customerCard.getCardId());
                    Card card = remoteCustomerService.cardInfo(map);
                    if (card != null){
                        customerCard.setCardLevel(card.getCardLevel());
                    }
                    else {
                        throw new Exception("无效的会员卡");
                    }
                }
                else {
                    throw new Exception("会员卡没有关联卡id");
                }
            }

            customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
            com.ktgj.customer.api.domain.CustomerCard result = customerCards.get(0);

            if (result == null) {
                response.setMsg("会员卡信息获取失败！");
                response.setHasSuccess(false);
                return response;
            }
            CustomerCard card = result;
            String cardCode = null;
            if (card != null) {
                cardCode = card.getCardCode();
            }


            //订单基本信息
            FlightOrderInfo orderInfo = new FlightOrderInfo();

            SnowFlake snowFlake = new SnowFlake(1, 1);
            orderInfo.setOrderId(snowFlake.nextId()); //主键
            //会员信息
            orderInfo.setCustomerId(data.getCustomerId());
            orderInfo.setCustomerName(data.getCustomerName());
            orderInfo.setCustomerCardId(cardCode); //会员卡号
            orderInfo.setStopCount(moRequest.stopCount);
            orderInfo.setExpectOutTime(moRequest.expectOutTime);
            orderInfo.setSourceTypeId(moRequest.sourceTypeId);
            orderInfo.setContactPhone(moRequest.Contacts.ContactMobile);

            //乘客数量
            orderInfo.setGuestNum(Long.valueOf(moRequest.ListMoPassenger.size()));
            //订单类型(1 散客)
            orderInfo.setOrderTypenew("1");
            //行程类型(单程、往返)
            if (moRequest.TripType == EnumHelper.TripType.单程.getValue()) {
                orderInfo.setTripType(FlightOrderConstants.ow.toString());
            } else if (moRequest.TripType == EnumHelper.TripType.往返.getValue()) {
                orderInfo.setTripType(FlightOrderConstants.rt.toString());
            }

            //联系人信息
            orderInfo.setContactMobile(data.getContractPhoneOne());
            orderInfo.setCustomerName(data.getCustomerName());
            //性别：1女 2男 TODO 后期完善
            /*if (data.getCustomerSex().equals("female")) {
                orderInfo.setContactSex(FlightOrderConstants.female.toString());
            } else {
                orderInfo.setContactSex(FlightOrderConstants.male.toString());
            }*/
            orderInfo.setTicketWay(changType);
            orderInfo.setGuestPymtStsId(FlightOrderConstants.waitPay.getValue()); //未支付
            orderInfo.setStatus(FlightOrderConstants.waitPay.getValue());
            if (moRequest.usePoint) {
                orderInfo.setPoints(moRequest.point);
            }
            if (moRequest.useDeposit) {
                orderInfo.setDepositAmount(moRequest.deposit);
            }
            if (moRequest.couponId != null && moRequest.couponId != 0) {
                orderInfo.setCouponId(moRequest.couponId);
            }

            //保存订单基本信息
            orderInfoService.insertFlightOrderInfoDatabase(orderInfo);

            if (moRequest.iternary != null) {
                if (moRequest.iternary.getPostWay().equals(1L)) {
                    moRequest.iternary.setPayState(FlightOrderConstants.waitPay.getValue());
                    moRequest.iternary.setPayCost(new BigDecimal(10));
                    moRequest.iternary.setOrderState(1L);
                } else if (moRequest.iternary.getPostWay().equals(2L)) {
                    moRequest.iternary.setPayCost(new BigDecimal(0));
                    moRequest.iternary.setOrderState(0L);
                }
                moRequest.iternary.setRefundStatus(0L);
                moRequest.iternary.setOrderId(String.valueOf(orderInfo.getOrderId()));
                moRequest.iternary.setCustomerId(String.valueOf(data.getCustomerId()));
                moRequest.iternary.setCreateTime(new Date());
                flightOrderIternaryMapper.insertFlightOrderIternary(moRequest.iternary);
                FlightDeliverAssign assign = new FlightDeliverAssign();
                assign.setOrderId(orderInfo.getOrderId());
                assign.setContactName(moRequest.iternary.getAddressOwner());
                assign.setContactMobile(moRequest.iternary.getContactMobile());
                assign.setContactPhone(moRequest.iternary.getContactMobile());
                assign.setContactEmail(moRequest.iternary.getContactEmail());
                assign.setContactAddress(moRequest.iternary.getContactAddress());
                assign.setIsneedinvoice(0L);
                assign.setIscanprinteticket(1L);
                assign.setIsprintover(0L);
                assign.setTripinvoice(1L);
                flightDeliverAssignMapper.insertFlightDeliverAssign(assign);
            }

            if (moRequest.invoice != null) {
                moRequest.invoice.setOrderId(String.valueOf(orderInfo.getOrderId()));
                moRequest.invoice.setInvoiceItem("机票款");
                moRequest.invoice.setCreateTime(new Date());
                moRequest.invoice.setLastDate(new Date());
                moRequest.invoice.setStatus(1L);
                flightOrderInvoiceMapper.insertFlightOrderInvoice(moRequest.invoice);
                InvoiceInvoiceOrder invoiceInvoiceOrder = new InvoiceInvoiceOrder();
                invoiceInvoiceOrder.setJsjid(String.valueOf(data.getCustomerId()));
                invoiceInvoiceOrder.setOrdernum(String.valueOf(orderInfo.getOrderId()));
                invoiceInvoiceOrder.setState(1L);
                invoiceInvoiceOrder.setType(1L);
                invoiceInvoiceOrder.setSort(moRequest.invoice.getInvoiceType());
                if (moRequest.iternary != null)
                    invoiceInvoiceOrder.setHaveitinerary(1L);
                else
                    invoiceInvoiceOrder.setHaveitinerary(2L);
                invoiceInvoiceOrder.setTitle(moRequest.invoice.getInvoiceName());
                invoiceInvoiceOrder.setTaxno(moRequest.invoice.getTaxId());
                invoiceInvoiceOrder.setSellertitle(moRequest.invoice.getCompanyId());
                invoiceInvoiceOrder.setSellertaxno("91110105599660274U");
                invoiceInvoiceOrder.setSelleraddress(moRequest.invoice.getCompanyAddress());
                invoiceInvoiceOrder.setSellerbankaccount(moRequest.invoice.getBankAccount());
                invoiceInvoiceOrder.setSellerphone(moRequest.invoice.getCompanyPhone());
                invoiceInvoiceOrder.setSourceway(1L);
                invoiceInvoiceOrder.setGoodsname("机票款");
                if (moRequest.sourceTypeId.equals("Crm"))
                    invoiceInvoiceOrder.setSourceappid(1L);
                else
                    invoiceInvoiceOrder.setSourceappid(15L); //TODO 后期完善
                invoiceInvoiceOrder.setTaxrate(new BigDecimal(0.06));
                invoiceInvoiceOrder.setTaxamount(moRequest.payamount);
                invoiceInvoiceOrder.setCreateTime(new Date());
                invoiceInvoiceOrder.setUpdateTime(new Date());
                invoiceInvoiceOrder.setAddress(moRequest.invoice.getAddress());
                invoiceInvoiceOrder.setPhone(moRequest.invoice.getPhone());
                invoiceInvoiceOrder.setBankaccount(moRequest.invoice.getBankaccount());
                invoiceInvoiceOrder.setBankname(moRequest.invoice.getBankname());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String passengerName = "";
                for (MoPassenger passenger : moRequest.ListMoPassenger) {
                    passengerName += passenger.PassengerName + " ";
                }
                if (moRequest.TripType == EnumHelper.TripType.单程.getValue()) {
                    if (moRequest.ListGoSegment.size() == 2) {
                        String depDate = dateFormat.format(moRequest.ListGoSegment.get(0).DepDate);
                        String orgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).OrgAirport).getAirportCityName();
                        String dstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(1).DstAirport).getAirportCityName();
                        invoiceInvoiceOrder.setRemark(depDate + " " + orgCityName + "-" + dstCityName + " " + passengerName.substring(0, passengerName.length() - 1));
                    } else {
                        String depDate = dateFormat.format(moRequest.ListGoSegment.get(0).DepDate);
                        String orgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).OrgAirport).getAirportCityName();
                        String dstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).DstAirport).getAirportCityName();
                        invoiceInvoiceOrder.setRemark(depDate + " " + orgCityName + "-" + dstCityName + " " + passengerName.substring(0, passengerName.length() - 1));
                    }
                } else {
                    String goDepDate = dateFormat.format(moRequest.ListGoSegment.get(0).DepDate);
                    String backDepDate = dateFormat.format(moRequest.ListBackSegment.get(0).DepDate);
                    String goOrgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).OrgAirport).getAirportCityName();
                    String goDstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(1).DstAirport).getAirportCityName();
                    String backOrgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListBackSegment.get(0).OrgAirport).getAirportCityName();
                    String backDstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListBackSegment.get(1).DstAirport).getAirportCityName();
                    invoiceInvoiceOrder.setRemark(goDepDate + " " + goOrgCityName + "-" + goDstCityName + " " + backDepDate + " " + backOrgCityName + "-" + backDstCityName + passengerName.substring(0, passengerName.length() - 1));
                }
                InvoiceDelivery invoiceDeliverie = new InvoiceDelivery();
                invoiceDeliverie.setDeliverytype(2L);
                invoiceDeliverie.setExpressdeliverystate(1L);
                invoiceDeliverie.setEmailstate(1L);
                /*invoiceDeliverie.setConsignee(moRequest.invoice.getConsignee());
                invoiceDeliverie.setAddress(moRequest.invoice.getInvoicdeAddress());
                invoiceDeliverie.setPhonenumber(moRequest.invoice.getPhonenumber());*/
                invoiceDeliverie.setEmail(moRequest.invoice.getEmail());
                invoiceInvoiceOrder.setInvoiceDeliverie(invoiceDeliverie);
                remotePayService.add(invoiceInvoiceOrder);
            }

            CustomerIdVoApi idVo = new CustomerIdVoApi();
            idVo.setCustomerId(customerInfo.getData().getCustomerId());
            //CustomerIdVoApi customerIdApi = remoteCustomerService.customerIdApi(idVo);

            if (moRequest.TripType == EnumHelper.TripType.单程.getValue()) {
                if (moRequest.ListGoSegment.size() == 2) {
                    saveOrderInfoTickets(orderInfo.getOrderId(), moRequest);
                    saveOrderInfoTicket(orderInfo.getOrderId(), moRequest);
                } else {
                    saveOrderInfoTickets(orderInfo.getOrderId(), moRequest);
                }
            } else {
                //去程
                saveOrderInfoTickets(orderInfo.getOrderId(), moRequest);
                //回程
                String flightNo = moRequest.ListBackSegment.get(0).FlightNo;
                String cabin = moRequest.ListBackSegment.get(0).Cabin;
                String airline = moRequest.ListBackSegment.get(0).Airline;
                //BigDecimal oilFee = moRequest.ListBackSegment.get(0).OilFee;
                //BigDecimal tax = moRequest.ListBackSegment.get(0).Tax;
                Date depDate = moRequest.ListBackSegment.get(0).DepDate;
                Date arrDate = moRequest.ListBackSegment.get(0).ArrDate;
                String DstAirport = moRequest.ListBackSegment.get(0).DstAirport; //抵达机场三字码
                String OrgAirport = moRequest.ListBackSegment.get(0).OrgAirport; //出发机场三字码
                String flightType = moRequest.ListBackSegment.get(0).PlaneStyle; //机型
                //BigDecimal Price = moRequest.ListBackSegment.get(0).Price; //全价
                String orgTerminal = moRequest.ListBackSegment.get(0).orgTerminal; //出发机场航站楼
                String dstTerminal = moRequest.ListBackSegment.get(0).dstTerminal; //抵达机场航站楼
                String cabinLevel = moRequest.ListBackSegment.get(0).cabinLevel; //舱位等级
                String stopDesc = moRequest.ListBackSegment.get(0).stopDesc; //经停时间
                //保存订单详细信息
                for (MoPassenger moPassenger : moRequest.ListMoPassenger) {

                    FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
                    //基本订单ID
                    infoTickets.setOrderId(orderInfo.getOrderId());
                    String birthByIdCard = IDCardUtil.getBirthFormatByIdCard(moPassenger.IDNO);
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    infoTickets.setGuestBirthday(format.parse(birthByIdCard));
                    infoTickets.setTripNum(Long.valueOf(moRequest.ListGoSegment.size() + moRequest.ListBackSegment.size()));
                    //航司
                    infoTickets.setAirliner(airline);
                    //航段类型
                    infoTickets.setTripType(FlightOrderConstants.rt.toString());
                    //航班号
                    infoTickets.setFlight(flightNo);
                    //乘客性别
                    infoTickets.setGuestSex(IDCardUtil.getGenderByIdCard(moPassenger.IDNO));
                    //基建
                    infoTickets.setAirportFee(moPassenger.AirportTax);
                    //燃油
                    infoTickets.setFuelFee(moPassenger.FuelTax);
                    //出发时间
                    infoTickets.setDepartureTime(depDate);
                    //手机号
                    infoTickets.setGuestMobile(moPassenger.PassengerMobile);
                    //仓位
                    infoTickets.setCabin(cabin);
                    //舱位等级
                    infoTickets.setCabinGrade(cabinLevel);
                    //到达时间
                    infoTickets.setArrivalTime(arrDate);
                    //机型
                    infoTickets.setFlightType(flightType);
                    //全价
                    //infoTickets.setFullPrice(Price);
                    //票面价
                    infoTickets.setTicketPrice(moPassenger.backTicketAmount);
                    infoTickets.setOrgPrice(moPassenger.backOrgPrice);
                    infoTickets.setReturnCash(moPassenger.returnMoney);
                    infoTickets.setStopDesc(stopDesc); //经停时间

                    infoTickets.setIdTypeId(Long.valueOf(moPassenger.IDType));

                    //乘客类型
                    //乘客类型(成人>12岁=1,儿童2-12岁=2,婴儿2岁=3）
                    int passengerType = moPassenger.PassengerType;
                    String pasType = "成人";
                    //乘客姓名
                    infoTickets.setGuestName(moPassenger.PassengerName);
                    if (passengerType == EnumHelper.PassengerType.儿童.getValue()) {
                        pasType = EnumHelper.PassengerType.儿童.toString();
                    } else if (passengerType == EnumHelper.PassengerType.婴儿.getValue()) {
                        pasType = EnumHelper.PassengerType.婴儿.toString();
                    } else if (passengerType == EnumHelper.PassengerType.成人.getValue()) {
                        pasType = EnumHelper.PassengerType.成人.toString();
                    } else {
                        pasType = EnumHelper.PassengerType.未识别.toString();
                    }
                    infoTickets.setGuestType(pasType);
                    //证件号
                    infoTickets.setGuestIdno(moPassenger.IDNO);

                    //机场信息
                    Airport depAirport = airportService.getAirPortNameByRirPortCode(OrgAirport);
                    infoTickets.setOrgAirport(OrgAirport);
                    infoTickets.setDepTerm(depAirport.getAirnamesort() + orgTerminal);//起飞机场航站楼
                    infoTickets.setDeparture(depAirport.getAirportCityName()); //出发城市

                    Airport ArrAirport = airportService.getAirPortNameByRirPortCode(DstAirport);
                    infoTickets.setDstAirport(DstAirport);
                    infoTickets.setArrTerm(ArrAirport.getAirnamesort() + dstTerminal);//到达机场航站楼
                    infoTickets.setArrival(ArrAirport.getAirportCityName());//抵达城市
                    infoTickets.setStatus(FlightOrderConstants.waitPay.getValue());

                    //保存信息
                    orderInfoTicketsService.insertFlightOrderInfoTickets(infoTickets);
                }
            }
            List<FlightOrderInfoTickets> ticketsList = orderInfoTicketsService.selectOrderInfoTicketByOrderId(orderInfo.getOrderId());
            response.setOrderId(String.valueOf(orderInfo.getOrderId()));
            response.setHasSuccess(true);
            if (response.isHasSuccess()) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String newDate = dateFormat.format(new Date());
                Map<String, String> map = new HashMap<>();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (orderInfo.getTripType().equals(FlightOrderConstants.ow.toString())) {
                    map.put("messageContent", "您在" + newDate + "日，预定：" + format.format(ticketsList.get(0).getDepartureTime()) + ticketsList.get(0).getDeparture() + "-" + ticketsList.get(0).getArrival() + "\t" + ticketsList.get(0).getFlight() + "，请在规定时间内支付，以免影响您的日程");
                } else if (orderInfo.getTripType().equals(FlightOrderConstants.rt.toString())) {
                    map.put("messageContent", "您在" + newDate + "日，预定：去程：" + format.format(ticketsList.get(0).getDepartureTime()) + ticketsList.get(0).getDeparture() + "-" + ticketsList.get(0).getArrival() + "\t" + ticketsList.get(0).getFlight() + ". 返程：" + format.format(ticketsList.get(1).getDepartureTime()) + ticketsList.get(1).getDeparture() + "-" + ticketsList.get(1).getArrival() + "\t" + ticketsList.get(1).getFlight() + "，请在规定时间内支付，以免影响您的日程");
                }
                map.put("businessType", BusinessTypeConstants.flight.getValue());
                map.put("businessOrderId", String.valueOf(orderInfo.getOrderId()));
                map.put("customerId", String.valueOf(data.getCustomerId()));
                customerService.addCustomerMessage(map);
            }
            return response;

        } catch (ParseException e) {
            response.setHasSuccess(false);
            response.setMsg("系统异常");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 保存订单信息CRM
     */
    private FlightOrderResponse saveOrderCRM(MoCreateOrderRequest moRequest, Long customerId, String changType) {
        FlightOrderResponse response = new FlightOrderResponse();
        try {
            //获取会员信息
            R<Customer> customerInfo = customerService.getCustomerId(customerId);
            Customer data = customerInfo.getData();
            if (data == null) {
                response.setMsg("会员信息获取失败！");
                response.setHasSuccess(false);
                return response;
            }
            //获取会员卡信息
            List<CustomerCard> customerCards = customerService.queryCardIdByCustomerId(data.getCustomerId());

            for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
                if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                    Map<String, Object> map = new HashMap<>();
                    map.put("cardId", customerCard.getCardId());
                    Card card = remoteCustomerService.cardInfo(map);
                    if (card != null){
                        customerCard.setCardLevel(card.getCardLevel());
                    }
                    else {
                        throw new Exception("无效的会员卡");
                    }
                }
                else {
                    throw new Exception("会员卡没有关联卡id");
                }
            }

            customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
            com.ktgj.customer.api.domain.CustomerCard result = customerCards.get(0);

            if (result == null) {
                response.setMsg("会员卡信息获取失败！");
                response.setHasSuccess(false);
                return response;
            }
            CustomerCard card = result;
            String cardCode = null;
            if (card != null) {
                cardCode = card.getCardCode();
            }


            //订单基本信息
            FlightOrderInfo orderInfo = new FlightOrderInfo();

            SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
            orderInfo.setOrderId(snowflakeUtils.nextId()); //主键
            //会员信息
            orderInfo.setCustomerId(data.getCustomerId());
            orderInfo.setCustomerName(data.getCustomerName());
            orderInfo.setCustomerCardId(cardCode); //会员卡号
            orderInfo.setStopCount(moRequest.stopCount);
            orderInfo.setExpectOutTime(moRequest.expectOutTime);
            orderInfo.setSourceTypeId(moRequest.sourceTypeId);
            orderInfo.setPnr(moRequest.pnr);
            orderInfo.setBigpnr(moRequest.bigPnr);
            orderInfo.setPnrstatus("success");
            orderInfo.setActionCode(moRequest.actionCode);
            orderInfo.setPayAmount(new BigDecimal(0.1));
            orderInfo.setSourceTypeId("Crm");
            //乘客数量
            orderInfo.setGuestNum(Long.valueOf(moRequest.ListMoPassenger.size()));
            orderInfo.setTicketAmount(moRequest.totalPay);
            //订单类型(1 散客)
            orderInfo.setOrderTypenew("1");
            //行程类型(单程、往返)
            if (moRequest.TripType == EnumHelper.TripType.单程.getValue()) {
                orderInfo.setTripType(FlightOrderConstants.ow.toString());
            } else if (moRequest.TripType == EnumHelper.TripType.往返.getValue()) {
                orderInfo.setTripType(FlightOrderConstants.rt.toString());
            }

            //联系人信息
            orderInfo.setContactMobile(data.getContractPhoneOne());
            orderInfo.setCustomerName(data.getCustomerName());
            //性别：1女 2男 TODO 后期完善
            /*if (data.getCustomerSex().equals("female")) {
                orderInfo.setContactSex(FlightOrderConstants.female.toString());
            } else {
                orderInfo.setContactSex(FlightOrderConstants.male.toString());
            }*/
            orderInfo.setTicketWay(changType);
            orderInfo.setGuestPymtStsId(FlightOrderConstants.waitPay.getValue()); //未支付
            orderInfo.setStatus(FlightOrderConstants.waitPay.getValue());
            if (moRequest.usePoint) {
                orderInfo.setPoints(moRequest.point);
            }
            if (moRequest.useDeposit) {
                orderInfo.setDepositAmount(moRequest.deposit);
            }
            if (moRequest.couponId != null && moRequest.couponId != 0) {
                orderInfo.setCouponId(moRequest.couponId);
            }
            if (changType.equals(EnumHelper.RequestType.LinkStar.toString())) {
                //获取出票渠道主表信息
                FlightChannelRule channelRule = channelRuleService.selectFlightChannelInfo(moRequest.ListGoSegment.get(0).Airline);
                //获取出票渠道详细信息
                FlightInterface flightInterface = interfaceService.selectFlightInterfaceByAirCodeAndType(channelRule.getAirlinerId(), Long.valueOf(channelRule.getPeksourcetype()));
                if (flightInterface.getSourcetype() == Integer.parseInt(FlightOrderConstants.bsp.getValue())) {
                    orderInfo.setTicketChannel(FlightOrderConstants.bsp.toString());
                } else {
                    orderInfo.setTicketChannel(FlightOrderConstants.b2b.toString());
                }
            } else if (changType.equals(EnumHelper.RequestType.Qunar.toString()) || changType.equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
                orderInfo.setTicketChannel(FlightOrderConstants.Outsourcing.toString());
            } else if (changType.equals(EnumHelper.RequestType.Spring.toString()) || changType.equals(EnumHelper.RequestType.DR.toString()) || changType.equals(EnumHelper.RequestType.G5.toString())) {
                orderInfo.setTicketChannel(FlightOrderConstants.LinkAirline.toString());
            }

            //保存订单基本信息
            orderInfoService.insertFlightOrderInfoDatabase(orderInfo);

            if (moRequest.iternary != null) {
                if (moRequest.iternary.getPostWay().equals(1L)) {
                    moRequest.iternary.setPayState(FlightOrderConstants.waitPay.getValue());
                    moRequest.iternary.setPayCost(new BigDecimal(10));
                    moRequest.iternary.setOrderState(1L);
                } else if (moRequest.iternary.getPostWay().equals(2L)) {
                    moRequest.iternary.setPayCost(new BigDecimal(0));
                    moRequest.iternary.setOrderState(0L);
                }
                moRequest.iternary.setRefundStatus(0L);
                moRequest.iternary.setOrderId(String.valueOf(orderInfo.getOrderId()));
                moRequest.iternary.setCustomerId(String.valueOf(data.getCustomerId()));
                moRequest.iternary.setCreateTime(new Date());
                flightOrderIternaryMapper.insertFlightOrderIternary(moRequest.iternary);
                FlightDeliverAssign assign = new FlightDeliverAssign();
                assign.setOrderId(orderInfo.getOrderId());
                assign.setContactName(moRequest.iternary.getAddressOwner());
                assign.setContactMobile(moRequest.iternary.getContactMobile());
                assign.setContactPhone(moRequest.iternary.getContactMobile());
                assign.setContactEmail(moRequest.iternary.getContactEmail());
                assign.setContactAddress(moRequest.iternary.getContactAddress());
                assign.setIsneedinvoice(0L);
                assign.setIscanprinteticket(1L);
                assign.setIsprintover(0L);
                assign.setTripinvoice(1L);
                flightDeliverAssignMapper.insertFlightDeliverAssign(assign);
            }

            if (moRequest.invoice != null) {
                moRequest.invoice.setOrderId(String.valueOf(orderInfo.getOrderId()));
                moRequest.invoice.setInvoiceItem("机票款");
                moRequest.invoice.setCreateTime(new Date());
                moRequest.invoice.setLastDate(new Date());
                moRequest.invoice.setStatus(1L);
                flightOrderInvoiceMapper.insertFlightOrderInvoice(moRequest.invoice);
                InvoiceInvoiceOrder invoiceInvoiceOrder = new InvoiceInvoiceOrder();
                invoiceInvoiceOrder.setJsjid(String.valueOf(data.getCustomerId()));
                invoiceInvoiceOrder.setOrdernum(String.valueOf(orderInfo.getOrderId()));
                invoiceInvoiceOrder.setState(1L);
                invoiceInvoiceOrder.setType(1L);
                invoiceInvoiceOrder.setSort(moRequest.invoice.getInvoiceType());
                if (moRequest.iternary != null)
                    invoiceInvoiceOrder.setHaveitinerary(1L);
                else
                    invoiceInvoiceOrder.setHaveitinerary(2L);
                invoiceInvoiceOrder.setTitle(moRequest.invoice.getInvoiceName());
                invoiceInvoiceOrder.setTaxno(moRequest.invoice.getTaxId());
                invoiceInvoiceOrder.setSellertitle(moRequest.invoice.getCompanyId());
                invoiceInvoiceOrder.setSellertaxno("91110105599660274U");
                invoiceInvoiceOrder.setSelleraddress(moRequest.invoice.getCompanyAddress());
                invoiceInvoiceOrder.setSellerbankaccount(moRequest.invoice.getBankAccount());
                invoiceInvoiceOrder.setSellerphone(moRequest.invoice.getCompanyPhone());
                invoiceInvoiceOrder.setSourceway(1L);
                invoiceInvoiceOrder.setGoodsname("机票款");
                if (moRequest.sourceTypeId.equals("Crm"))
                    invoiceInvoiceOrder.setSourceappid(1L);
                else
                    invoiceInvoiceOrder.setSourceappid(15L); //TODO 后期完善
                invoiceInvoiceOrder.setTaxrate(new BigDecimal(0.06));
                invoiceInvoiceOrder.setTaxamount(moRequest.payamount);
                invoiceInvoiceOrder.setCreateTime(new Date());
                invoiceInvoiceOrder.setUpdateTime(new Date());
                invoiceInvoiceOrder.setAddress(moRequest.invoice.getAddress());
                invoiceInvoiceOrder.setPhone(moRequest.invoice.getPhone());
                invoiceInvoiceOrder.setBankaccount(moRequest.invoice.getBankaccount());
                invoiceInvoiceOrder.setBankname(moRequest.invoice.getBankname());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String passengerName = "";
                for (MoPassenger passenger : moRequest.ListMoPassenger) {
                    passengerName += passenger.PassengerName + " ";
                }
                if (moRequest.TripType == EnumHelper.TripType.单程.getValue()) {
                    if (moRequest.ListGoSegment.size() == 2) {
                        String depDate = dateFormat.format(moRequest.ListGoSegment.get(0).DepDate);
                        String orgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).OrgAirport).getAirportCityName();
                        String dstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(1).DstAirport).getAirportCityName();
                        invoiceInvoiceOrder.setRemark(depDate + " " + orgCityName + "-" + dstCityName + " " + passengerName.substring(0, passengerName.length() - 1));
                    } else {
                        String depDate = dateFormat.format(moRequest.ListGoSegment.get(0).DepDate);
                        String orgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).OrgAirport).getAirportCityName();
                        String dstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).DstAirport).getAirportCityName();
                        invoiceInvoiceOrder.setRemark(depDate + " " + orgCityName + "-" + dstCityName + " " + passengerName.substring(0, passengerName.length() - 1));
                    }
                } else {
                    String goDepDate = dateFormat.format(moRequest.ListGoSegment.get(0).DepDate);
                    String backDepDate = dateFormat.format(moRequest.ListBackSegment.get(0).DepDate);
                    String goOrgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(0).OrgAirport).getAirportCityName();
                    String goDstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListGoSegment.get(1).DstAirport).getAirportCityName();
                    String backOrgCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListBackSegment.get(0).OrgAirport).getAirportCityName();
                    String backDstCityName = airportService.getAirPortNameByRirPortCode(moRequest.ListBackSegment.get(1).DstAirport).getAirportCityName();
                    invoiceInvoiceOrder.setRemark(goDepDate + " " + goOrgCityName + "-" + goDstCityName + " " + backDepDate + " " + backOrgCityName + "-" + backDstCityName + passengerName.substring(0, passengerName.length() - 1));
                }
                InvoiceDelivery invoiceDeliverie = new InvoiceDelivery();
                invoiceDeliverie.setDeliverytype(2L);
                invoiceDeliverie.setExpressdeliverystate(1L);
                invoiceDeliverie.setEmailstate(1L);
                /*invoiceDeliverie.setConsignee(moRequest.invoice.getConsignee());
                invoiceDeliverie.setAddress(moRequest.invoice.getInvoicdeAddress());
                invoiceDeliverie.setPhonenumber(moRequest.invoice.getPhonenumber());*/
                invoiceDeliverie.setEmail(moRequest.invoice.getEmail());
                invoiceInvoiceOrder.setInvoiceDeliverie(invoiceDeliverie);
                remotePayService.add(invoiceInvoiceOrder);
            }

            CustomerIdVoApi idVo = new CustomerIdVoApi();
            idVo.setCustomerId(customerInfo.getData().getCustomerId());
            //CustomerIdVoApi customerIdApi = remoteCustomerService.customerIdApi(idVo);
            if (moRequest.TripType == EnumHelper.TripType.单程.getValue()) {
                if (moRequest.ListGoSegment.size() == 2) {
                    saveOrderInfoTickets(orderInfo.getOrderId(), moRequest);
                    saveOrderInfoTicket(orderInfo.getOrderId(), moRequest);
                } else {
                    saveOrderInfoTickets(orderInfo.getOrderId(), moRequest);
                }
            } else {
                //去程
                saveOrderInfoTickets(orderInfo.getOrderId(), moRequest);
                //回程
                String flightNo = moRequest.ListBackSegment.get(0).FlightNo;
                String cabin = moRequest.ListBackSegment.get(0).Cabin;
                String airline = moRequest.ListBackSegment.get(0).Airline;
                BigDecimal oilFee = moRequest.ListBackSegment.get(0).OilFee;
                BigDecimal tax = moRequest.ListBackSegment.get(0).Tax;
                Date depDate = moRequest.ListBackSegment.get(0).DepDate;
                Date arrDate = moRequest.ListBackSegment.get(0).ArrDate;
                String DstAirport = moRequest.ListBackSegment.get(0).DstAirport; //抵达机场三字码
                String OrgAirport = moRequest.ListBackSegment.get(0).OrgAirport; //出发机场三字码
                String flightType = moRequest.ListBackSegment.get(0).PlaneStyle; //机型
                BigDecimal Price = moRequest.ListBackSegment.get(0).Price; //全价
                BigDecimal PrintPrice = moRequest.ListBackSegment.get(0).PrintPrice;//票面价
                String orgTerminal = moRequest.ListBackSegment.get(0).orgTerminal; //出发机场航站楼
                String dstTerminal = moRequest.ListBackSegment.get(0).dstTerminal; //抵达机场航站楼
                String cabinLevel = moRequest.ListBackSegment.get(0).cabinLevel; //舱位等级
                BigDecimal ticketAmount = moRequest.ListMoPassenger.get(0).TicketAmount; //票面价
                String stopDesc = moRequest.ListBackSegment.get(0).stopDesc; //经停时间
                //保存订单详细信息
                for (MoPassenger moPassenger : moRequest.ListMoPassenger) {

                    FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
                    //基本订单ID
                    infoTickets.setOrderId(orderInfo.getOrderId());
                    String birthByIdCard = IDCardUtil.getBirthFormatByIdCard(moPassenger.IDNO);
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    infoTickets.setGuestBirthday(format.parse(birthByIdCard));
                    infoTickets.setTicketPrice(ticketAmount);
                    infoTickets.setTripNum(Long.valueOf(moRequest.ListGoSegment.size() + moRequest.ListBackSegment.size()));
                    //航司
                    infoTickets.setAirliner(airline);
                    //航段类型
                    infoTickets.setTripType(FlightOrderConstants.rt.toString());
                    //航班号
                    infoTickets.setFlight(flightNo);
                    //乘客性别
                    infoTickets.setGuestSex(IDCardUtil.getGenderByIdCard(moPassenger.IDNO));
                    //基建
                    infoTickets.setAirportFee(tax);
                    //燃油
                    infoTickets.setFuelFee(oilFee);
                    //出发时间
                    infoTickets.setDepartureTime(depDate);
                    //手机号
                    infoTickets.setGuestMobile(moPassenger.PassengerMobile);
                    //仓位
                    infoTickets.setCabin(cabin);
                    //舱位等级
                    infoTickets.setCabinGrade(cabinLevel);
                    //到达时间
                    infoTickets.setArrivalTime(arrDate);
                    //机型
                    infoTickets.setFlightType(flightType);
                    //全价
                    infoTickets.setFullPrice(Price);
                    //票面价
                    infoTickets.setTicketPrice(PrintPrice);
                    //经停时间
                    infoTickets.setStopDesc(stopDesc);

                    infoTickets.setIdTypeId(Long.valueOf(moPassenger.IDType));

                    //乘客类型
                    //乘客类型(成人>12岁=1,儿童2-12岁=2,婴儿2岁=3）
                    int passengerType = moPassenger.PassengerType;
                    String pasType = "成人";
                    //乘客姓名
                    infoTickets.setGuestName(moPassenger.PassengerName);
                    if (passengerType == EnumHelper.PassengerType.儿童.getValue()) {
                        pasType = EnumHelper.PassengerType.儿童.toString();
                    } else if (passengerType == EnumHelper.PassengerType.婴儿.getValue()) {
                        pasType = EnumHelper.PassengerType.婴儿.toString();
                    } else if (passengerType == EnumHelper.PassengerType.成人.getValue()) {
                        pasType = EnumHelper.PassengerType.成人.toString();
                    } else {
                        pasType = EnumHelper.PassengerType.未识别.toString();
                    }
                    infoTickets.setGuestType(pasType);
                    //证件号
                    infoTickets.setGuestIdno(moPassenger.IDNO);

                    //机场信息
                    Airport depAirport = airportService.getAirPortNameByRirPortCode(OrgAirport);
                    infoTickets.setOrgAirport(OrgAirport);
                    infoTickets.setDepTerm(depAirport.getAirnamesort() + orgTerminal);//起飞机场航站楼
                    infoTickets.setDeparture(depAirport.getAirportCityName()); //出发城市

                    Airport ArrAirport = airportService.getAirPortNameByRirPortCode(DstAirport);
                    infoTickets.setDstAirport(DstAirport);
                    infoTickets.setArrTerm(depAirport.getAirnamesort() + dstTerminal);//到达机场航站楼
                    infoTickets.setArrival(ArrAirport.getAirportCityName());//抵达城市
                    infoTickets.setStatus(FlightOrderConstants.waitPay.getValue());

                    //保存信息
                    orderInfoTicketsService.insertFlightOrderInfoTickets(infoTickets);
                }
            }

            response.setOrderId(String.valueOf(orderInfo.getOrderId()));
            response.setHasSuccess(true);

            return response;

        } catch (ParseException e) {
            response.setHasSuccess(false);
            response.setMsg("系统异常");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 保存订单详细（单程）
     *
     * @param orderId
     * @param moRequest
     */
    private void saveOrderInfoTickets(Long orderId, MoCreateOrderRequest moRequest) {
        String flightNo = moRequest.ListGoSegment.get(0).FlightNo;
        String cabin = moRequest.ListGoSegment.get(0).Cabin;
        String airline = moRequest.ListGoSegment.get(0).Airline;
        //BigDecimal oilFee = moRequest.ListGoSegment.get(0).OilFee;
        //BigDecimal tax = moRequest.ListGoSegment.get(0).Tax;
        Date depDate = moRequest.ListGoSegment.get(0).DepDate;
        Date arrDate = moRequest.ListGoSegment.get(0).ArrDate;
        String DstAirport = moRequest.ListGoSegment.get(0).DstAirport; //抵达机场三字码
        String OrgAirport = moRequest.ListGoSegment.get(0).OrgAirport; //出发机场三字码
        String flightType = moRequest.ListGoSegment.get(0).PlaneStyle; //机型
        //BigDecimal Price = moRequest.ListGoSegment.get(0).Price; //全价
        String orgTerminal = moRequest.ListGoSegment.get(0).orgTerminal; //出发机场航站楼
        String dstTerminal = moRequest.ListGoSegment.get(0).dstTerminal; //抵达机场航站楼
        String cabinLevel = moRequest.ListGoSegment.get(0).cabinLevel; //舱位等级
        String stopDesc = moRequest.ListGoSegment.get(0).stopDesc; //经停时间
        try {
            //保存订单详细信息
            for (MoPassenger moPassenger : moRequest.ListMoPassenger) {

                FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
                //基本订单ID
                infoTickets.setOrderId(orderId);
                //乘客生日
                String birthByIdCard = IDCardUtil.getBirthFormatByIdCard(moPassenger.IDNO);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                infoTickets.setGuestBirthday(format.parse(birthByIdCard));
                infoTickets.setTripNum(Long.valueOf(moRequest.ListGoSegment.size() + moRequest.ListBackSegment.size()));
                //航司
                infoTickets.setAirliner(airline);
                //航段类型
                infoTickets.setTripType(FlightOrderConstants.ow.toString());
                //航班号
                infoTickets.setFlight(flightNo);
                //乘客性别
                infoTickets.setGuestSex(IDCardUtil.getGenderByIdCard(moPassenger.IDNO));
                //基建
                infoTickets.setAirportFee(moPassenger.AirportTax);
                //燃油
                infoTickets.setFuelFee(moPassenger.FuelTax);
                //出发时间
                infoTickets.setDepartureTime(depDate);
                //手机号
                infoTickets.setGuestMobile(moPassenger.PassengerMobile);
                //仓位
                infoTickets.setCabin(cabin);
                //舱位等级
                infoTickets.setCabinGrade(cabinLevel);
                //到达时间
                infoTickets.setArrivalTime(arrDate);
                //机型
                infoTickets.setFlightType(flightType);
                //全价
                //infoTickets.setFullPrice(Price);
                //票面价
                infoTickets.setTicketPrice(moPassenger.TicketAmount);
                infoTickets.setOrgPrice(moPassenger.orgPrice);
                infoTickets.setReturnCash(moPassenger.returnMoney);
                infoTickets.setStopDesc(stopDesc); //经停时间

                infoTickets.setIdTypeId(Long.valueOf(moPassenger.IDType));

                //乘客类型
                //乘客类型(成人>12岁=1,儿童2-12岁=2,婴儿2岁=3）
                int passengerType = moPassenger.PassengerType;
                String pasType = "成人";
                if (passengerType == EnumHelper.PassengerType.儿童.getValue()) {
                    pasType = EnumHelper.PassengerType.儿童.toString();
                } else if (passengerType == EnumHelper.PassengerType.婴儿.getValue()) {
                    pasType = EnumHelper.PassengerType.婴儿.toString();
                } else if (passengerType == EnumHelper.PassengerType.成人.getValue()) {
                    pasType = EnumHelper.PassengerType.成人.toString();
                } else {
                    pasType = EnumHelper.PassengerType.未识别.toString();
                }
                //乘客姓名
                infoTickets.setGuestName(moPassenger.PassengerName);
                infoTickets.setGuestType(pasType);
                //证件号
                infoTickets.setGuestIdno(moPassenger.IDNO);

                //机场信息
                Airport depAirport = airportService.getAirPortNameByRirPortCode(OrgAirport);
                infoTickets.setOrgAirport(OrgAirport);
                infoTickets.setDepTerm(depAirport.getAirnamesort() + orgTerminal);//起飞机场航站楼
                infoTickets.setDeparture(depAirport.getAirportCityName()); //出发城市

                Airport ArrAirport = airportService.getAirPortNameByRirPortCode(DstAirport);
                infoTickets.setDstAirport(DstAirport);
                infoTickets.setArrTerm(ArrAirport.getAirnamesort() + dstTerminal);//到达机场航站楼
                infoTickets.setArrival(ArrAirport.getAirportCityName());//抵达城市
                infoTickets.setStatus(FlightOrderConstants.waitPay.getValue());

                //保存信息
                orderInfoTicketsService.insertFlightOrderInfoTickets(infoTickets);
                if (moRequest.products != null && moRequest.products.size() > 0) {
                    moRequest.products.forEach(item -> {
                        if (moPassenger.IDNO.equals(item.getIdNo())) {
                            R<AssistProductApi> assistProductApiR = remoteCustomerService.queryAssistProduct(item.getProductId());
                            AssistProductApi productApi = assistProductApiR.getData();
                            if (assistProductApiR.getCode() == 200 && productApi != null) {
                                FlightOrderAssist orderAssist = new FlightOrderAssist();
                                orderAssist.setName(productApi.getName());
                                orderAssist.setPrice(productApi.getUnderlinePrice());
                                orderAssist.setAssistProductId(item.getProductId());
                                orderAssist.setOrderInfoTicketsId(infoTickets.getOrderInfoTicketsId());
                                if (productApi.getProductTypeid() != null && productApi.getProductTypeid() != 0) {
                                    orderAssist.setInsType(productApi.getProductType());
                                }
                                orderAssist.setStatus("wait");
                                flightOrderAssistService.insertFlightOrderAssist(orderAssist);
                            }
                        }
                    });
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 保存订单详细（中转）
     *
     * @param orderId
     * @param moRequest
     */
    private void saveOrderInfoTicket(Long orderId, MoCreateOrderRequest moRequest) {
        String flightNo = moRequest.ListGoSegment.get(1).FlightNo;
        String cabin = moRequest.ListGoSegment.get(1).Cabin;
        String airline = moRequest.ListGoSegment.get(1).Airline;
        //BigDecimal oilFee = moRequest.ListGoSegment.get(1).OilFee;
        //BigDecimal tax = moRequest.ListGoSegment.get(1).Tax;
        Date depDate = moRequest.ListGoSegment.get(1).DepDate;
        Date arrDate = moRequest.ListGoSegment.get(1).ArrDate;
        String DstAirport = moRequest.ListGoSegment.get(1).DstAirport; //抵达机场三字码
        String OrgAirport = moRequest.ListGoSegment.get(1).OrgAirport; //出发机场三字码
        String flightType = moRequest.ListGoSegment.get(1).PlaneStyle; //机型
        //BigDecimal Price = moRequest.ListGoSegment.get(1).Price; //全价
        String orgTerminal = moRequest.ListGoSegment.get(1).orgTerminal; //出发机场航站楼
        String dstTerminal = moRequest.ListGoSegment.get(1).dstTerminal; //抵达机场航站楼
        String cabinLevel = moRequest.ListGoSegment.get(1).cabinLevel; //舱位等级
        String stopDesc = moRequest.ListGoSegment.get(1).stopDesc; //经停时间
        try {
            //保存订单详细信息
            for (MoPassenger moPassenger : moRequest.ListMoPassenger) {

                FlightOrderInfoTickets infoTickets = new FlightOrderInfoTickets();
                //基本订单ID
                infoTickets.setOrderId(orderId);
                //乘客生日
                String birthByIdCard = IDCardUtil.getBirthFormatByIdCard(moPassenger.IDNO);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                infoTickets.setGuestBirthday(format.parse(birthByIdCard));
                infoTickets.setTripNum(Long.valueOf(moRequest.ListGoSegment.size() + moRequest.ListBackSegment.size()));
                //航司
                infoTickets.setAirliner(airline);
                //航段类型
                infoTickets.setTripType(FlightOrderConstants.rt.toString());
                //航班号
                infoTickets.setFlight(flightNo);
                //乘客性别
                infoTickets.setGuestSex(IDCardUtil.getGenderByIdCard(moPassenger.IDNO));
                //基建
                infoTickets.setAirportFee(moPassenger.AirportTax);
                //燃油
                infoTickets.setFuelFee(moPassenger.FuelTax);
                //出发时间
                infoTickets.setDepartureTime(depDate);
                //手机号
                infoTickets.setGuestMobile(moPassenger.PassengerMobile);
                //仓位
                infoTickets.setCabin(cabin);
                //舱位等级
                infoTickets.setCabinGrade(cabinLevel);
                //到达时间
                infoTickets.setArrivalTime(arrDate);
                //机型
                infoTickets.setFlightType(flightType);
                //全价
                //infoTickets.setFullPrice(Price);
                //票面价
                infoTickets.setTicketPrice(moPassenger.backTicketAmount);
                infoTickets.setOrgPrice(moPassenger.backOrgPrice);
                infoTickets.setReturnCash(moPassenger.returnMoney);
                infoTickets.setStopDesc(stopDesc); //经停时间

                infoTickets.setIdTypeId(Long.valueOf(moPassenger.IDType));

                //乘客类型
                //乘客类型(成人>12岁=1,儿童2-12岁=2,婴儿2岁=3）
                int passengerType = moPassenger.PassengerType;
                String pasType = "成人";
                //乘客姓名
                infoTickets.setGuestName(moPassenger.PassengerName);
                if (passengerType == EnumHelper.PassengerType.儿童.getValue()) {
                    pasType = EnumHelper.PassengerType.儿童.toString();
                } else if (passengerType == EnumHelper.PassengerType.婴儿.getValue()) {
                    pasType = EnumHelper.PassengerType.婴儿.toString();
                } else if (passengerType == EnumHelper.PassengerType.成人.getValue()) {
                    pasType = EnumHelper.PassengerType.成人.toString();
                } else {
                    pasType = EnumHelper.PassengerType.未识别.toString();
                }
                infoTickets.setGuestType(pasType);
                //证件号
                infoTickets.setGuestIdno(moPassenger.IDNO);

                //机场信息
                Airport depAirport = airportService.getAirPortNameByRirPortCode(OrgAirport);
                infoTickets.setOrgAirport(OrgAirport);
                infoTickets.setDepTerm(depAirport.getAirnamesort() + orgTerminal);//起飞机场航站楼
                infoTickets.setDeparture(depAirport.getAirportCityName()); //出发城市

                Airport ArrAirport = airportService.getAirPortNameByRirPortCode(DstAirport);
                infoTickets.setDstAirport(DstAirport);
                infoTickets.setArrTerm(ArrAirport.getAirnamesort() + dstTerminal);//到达机场航站楼
                infoTickets.setArrival(ArrAirport.getAirportCityName());//抵达城市
                infoTickets.setStatus(FlightOrderConstants.waitPay.getValue());

                //保存信息
                orderInfoTicketsService.insertFlightOrderInfoTickets(infoTickets);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private FlightOrderResponse createOrderResponse(MoCreateOrderResponse response, Long orderId) {
        FlightOrderResponse orderResponse = new FlightOrderResponse();
        FlightOrderInfo info = new FlightOrderInfo();
        info.setOrderId(orderId);
        if (response.IsSuccess) {
            info.setPnrstatus(FlightOrderConstants.success.toString());
            info.setPnrMark("预订成功");
            info.setPayAmount(response.PayAmount);
            info.setPnr(response.MainOrderID);

            orderResponse.setHasSuccess(true);
            orderResponse.setMsg("预订成功");
            orderResponse.setPayAmount(response.PayAmount);
            orderResponse.setOrderId(String.valueOf(orderId));

        } else {
            info.setPnrMark(response.ErrorMsg);
            info.setPnrstatus(FlightOrderConstants.fail.toString());

            orderResponse.setHasSuccess(false);
            orderResponse.setMsg("预订失败");
        }

        return orderResponse;
    }

    /**
     * 省份证的正则表达式^(d{15}|d{17}[dx])$
     * @param id    省份证号
     * @return    生日（yyyy-MM-dd）
     */
    public String extractYearMonthDayOfIdCard(String id) {
        String year = null;
        String month = null;
        String day = null;
        //正则匹配身份证号是否是正确的，15位或者17位数字+数字/x/X
        if (id.matches("^\\d{15}|\\d{17}[\\dxX]$")) {
            year = id.substring(6, 10);
            month = id.substring(10,12);
            day = id.substring(12,14);
        }else {
            System.out.println("身份证号码不匹配！");
            return null;
        }
        return year + "-" + month + "-" + day;
    }
}


